1 #include <u.h> 2 #include <libc.h> 3 4 void lock(Lock * l)5lock(Lock *l) 6 { 7 if(ainc(&l->key) == 1) 8 return; /* changed from 0 -> 1: we hold lock */ 9 /* otherwise wait in kernel */ 10 while(semacquire(&l->sem, 1) < 0){ 11 /* interrupted; try again */ 12 } 13 } 14 15 void unlock(Lock * l)16unlock(Lock *l) 17 { 18 if(adec(&l->key) == 0) 19 return; /* changed from 1 -> 0: no contention */ 20 semrelease(&l->sem, 1); 21 } 22 23 int canlock(Lock * l)24canlock(Lock *l) 25 { 26 if(ainc(&l->key) == 1) 27 return 1; /* changed from 0 -> 1: success */ 28 /* Undo increment (but don't miss wakeup) */ 29 if(adec(&l->key) == 0) 30 return 0; /* changed from 1 -> 0: no contention */ 31 semrelease(&l->sem, 1); 32 return 0; 33 } 34