1 #include <u.h> 2 #include <libc.h> 3 4 int 5 canlock(Lock *lk) 6 { 7 return !tas(&lk->key); 8 } 9 10 void 11 lock(Lock *lk) 12 { 13 int i; 14 15 /* easy case */ 16 if(canlock(lk)) 17 return; 18 19 /* for multi processor machines */ 20 for(i=0; i<100; i++) 21 if(canlock(lk)) 22 return; 23 24 for(i=0; i<100; i++) { 25 osyield(); 26 if(canlock(lk)) 27 return; 28 } 29 30 /* looking bad - make sure it is not a priority problem */ 31 for(i=0; i<12; i++) { 32 osmsleep(1<<i); 33 if(canlock(lk)) 34 return; 35 } 36 37 /* we are in trouble */ 38 for(;;) { 39 if(canlock(lk)) 40 return; 41 iprint("lock loop %ld: val=%d &lock=%ux pc=%ux\n", getpid(), lk->key, lk, getcallerpc(&lk)); 42 osmsleep(1000); 43 } 44 } 45 46 void 47 unlock(Lock *lk) 48 { 49 assert(lk->key); 50 lk->key = 0; 51 } 52 53 void 54 ilock(Lock *lk) 55 { 56 lock(lk); 57 } 58 59 void 60 iunlock(Lock *lk) 61 { 62 unlock(lk); 63 } 64 65