Whose Turn Is It
An engineer writes Peterson's algorithm from memory. Reasoning that turn records whose turn it is to enter, they set it to their own thread id:
int flag[2] = {0, 0};
int turn = 0;
void lock(int self) {
flag[self] = 1;
turn = self; // differs from Peterson's
while (flag[1 - self] == 1 && turn == 1 - self)
; // spin
}
void unlock(int self) { flag[self] = 0; }
Assume a sequentially consistent machine (no store reordering). Which interleaving puts both threads in the critical section at the same time?
Sign in to answer questions and track your progress
Sign In