flag[i] = 1;
while (flag[j])
{
if (turn ==
j)
{
flag[i] = 0;
while(turn == j)
;
flag[i] = 1;
}
}
/* enter C.S. */
/* exit C.S. */
turn = j;
flag[i] = 0;
This algorithm is called Dekker's solution.
j =
a++;
// execute in one atomic operation
a = 0;
Either come up with a solution to the C.S. problem using this facility or show that it cannot help.
#include "Exception.h"
#include "Semaphore.h"
#include <iostream.h>
const MaxStackSize = 100;
class
Stack
// throws an exception object when popping an empty stack, and when
pushing
into a full stack
{
private:
int s[MaxStackSize];
int
stackp;
// stack pointer
Exception *
e;
// For error handling
Semaphore *
sem;
// For mutual exclusion
public:
Stack();
~Stack()
{};
int Pop(void);
void Push(int item);
};
Stack::Stack()
{
stackp = MaxStackSize;
e = new Exception();
sem = new Semaphore(1);
}
int Stack::Pop(void)
{
P(sem)
if(stackp == MaxStackSize)
{
e->SetErrorMsg("Popping empty stack");
e->SetErrorLocation("Stack::Pop()");
throw(e);
}
V(sem);
return s[stackp++];
}
void Stack::Push(int item)
{
P(sem)
if(stackp == 0)
{
e->SetErrorMsg("Pushing to a full stack");
e->SetErrorLocation("Stack::Push()");
throw(e);
}
s[--stackp] = item;
V(sem);
}
The agent places two of the ingredients on the table. The smoker who has the remaining ingredient then makes and smokes a cigarette, signaling the agent on completion. The agent then puts out another two of the three ingredients, and the cycle repeats.
Assume the agent calls the procedure
void chooseIngredients(int *paper, int *tobacco, int *match);to randomly select 2 of the 3 ingredients. The routine randomly sets 2 of the values to "1" and one of the values to "0". You don't have to write this routine.
Write a program to synchronize the agent and smokers.
Variable Name Variable Type Initial Value Description
void parallelDo(int n, void *(function(void *)), void *arg[])parallelDo spawns off N worker threads. function is a pointer to a function, and arg[] is an array of arguments to that function (e.g., worker thread i is to execute (*function)(arg[i])). parallelDo returns once all worker threads have finished running the function.
Assume you are given mutex locks and condition variables with standard public interfaces.
Assume that you are given functions creating and destroying threads that are similar to those discussed in class:
void sthread_create(sthread_t *thrd,
void sthread_exit(void);
Implement this parallelDo function. Follow the coding standards specified in the handout. Important: follow an object-oriented style of programming - encapsulate all shared states in an object that manages access to it.