int turn = 0; /* shared control variable */ Pi: /* i is 0 or 1 */ while (turn != i) ; /* busy wait */ CSi; turn = 1 - i;
This solution from this page but it is only made for two processes. I tried to adapt it for $n$ processes like this:
turn = 0 // shared control variable i = turn; while (turn != i); // CS turn = (turn + 1) % n;
Does this work?
Asked By : Bassam Badr
Answered By : AJed
i = turn
and instead, let each of the $n$ processors have an id from ${1, dots, n}$. Then, you would let the processors go in sequence to the critical code. That is, assume a processor $i$ takes the token and left it. Then, it has to wait the other $n- 1$ to take the token if it want to take it again. The problem in this solution is the sequential method of taking the token. If you want to have something more efficient, then have a look at the Lamport’s bakery algorithm. The pseudocode of the algorithm is available in the site you provided, and it is explained in wikipedia. The idea of this algorithm is very simple in fact. There is a queue of processors that want to get the token. These processors enter the queue, and the first come is first served. In regard to the link you included in your question, this is done by these lines:
number[i] = max(number) + 1; // enter the queue ! ... ... while (number[j] != 0 && (number[j] < number[i] || number[j] == number[i] && j < i) ) // wait until your turn comes. ... Do your critical section ! ... ... number[i] = 0; // go out of the queue ..
Obviously, you can play around with this. But it is a neat way of implementing FIFO requests.
Best Answer from StackOverflow
Question Source : http://cs.stackexchange.com/questions/9056