





















































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!






















































2
**- O(n) words for one lock for mutual exclusion among n threads
4
5
7
8
10
11
type Lock = record slots: array [0..numprocs -1] of (has_lock, must_wait) := (has_lock, must_wait, must_wait, ..., must_wait) // each element of slots should lie in a different memory module or cache line int next_slot := 0 // parameter my_place, below, points to a private variable in an enclosing scope procedure acquire_lock (Lock *L, int *my_place) *my_place := fetch_and_increment (&L->next_slot) if *my_place mod numprocs = 0 // decrement to avoid problems with overflow; ignore return value atomic_add(&L->next_slot,-numprocs) my_place := my_place mod numprocs repeat while L->slots[my_place] = must_wait // spin L->slots[my_place] := must_wait // init for next time procedure release_lock (Lock *L, int my_place) L->slots[(my_place + 1) mod numprocs] := has_lock
13
14
type qnode = record qnode *next bool locked type qnode *Lock // initialized to nil // parameter I, below, points to a qnode record allocated (in an enclosing scope) in // shared memory locally-accessible to the invoking processor procedure acquire_lock (Lock *L, qnode *I) I->next := nil qnode *predecessor := fetch_and_store (L, I) if predecessor != nil // queue was non-empty I->locked := true predecessor->next := I repeat while I->locked // spin procedure release_lock (Lock *L, qnode *I) if I->next = nil // no known successor if compare_and_swap (L, I, nil) return // compare_and_swap returns true iff it stored repeat while I->next = nil // spin I->next->locked := false
16 tail 1 2 3 4 run spin spin
arriving
17 tail 1 2 3 4 run spin spin
arriving
19 tail 1 2 3 4 leaving spin spin
20 tail 2 3 4 run spin
leaving (^) spin