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?
Sign in to answer questions and track your progress
Sign In