White RoomNEW White Room DSA

Both Threads Walk In

typedef struct { int flag; } lock_t;

void lock(lock_t *l) {
    while (l->flag == 1)
        ;              // spin
    l->flag = 1;
}
void unlock(lock_t *l) { l->flag = 0; }

flag starts at 0. A timer interrupt lands where marked:

step Thread 1 Thread 2
1 while (flag == 1) reads 0, falls out
2 interrupt, switch to T2
3 while (flag == 1) reads 0, falls out
4 flag = 1
5 enters critical section, interrupt
6 flag = 1
7 enters critical section

After step 7, how many threads are inside the critical section, and what is flag?