Test Then Set

A first attempt at a lock, using only ordinary loads and stores:

typedef struct { int flag; } lock_t;

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

Two threads on two cores, flag starting at 0:

step Thread 1 Thread 2 flag
1 reads flag == 0, exits the loop 0
2 preempted reads flag == 0, exits the loop 0
3 sets flag = 1, enters 1
4 sets flag = 1, enters 1

Which replacement lock() body restores mutual exclusion on a multiprocessor?

A

while (CompareAndSwap(&m->flag, 1, 0) == 0) ;

B

while (TestAndSet(&m->flag, 1) == 1) ;

C

while (m->flag == 1) ; m->flag = 1; __sync_synchronize();

D

DisableInterrupts(); while (m->flag == 1) ; m->flag = 1; EnableInterrupts();