From b2cfc4e2e71d0f0a5113ddfbd93c8285cc4d74e4 Mon Sep 17 00:00:00 2001 From: rsc Date: Tue, 30 Sep 2003 17:47:41 +0000 Subject: Initial revision --- src/lib9/lock.c | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 src/lib9/lock.c (limited to 'src/lib9/lock.c') diff --git a/src/lib9/lock.c b/src/lib9/lock.c new file mode 100644 index 00000000..2da73626 --- /dev/null +++ b/src/lib9/lock.c @@ -0,0 +1,54 @@ +#include +#include +#include + +int _ntas; +static int +_xtas(void *v) +{ + int x; + +_ntas++; + x = _tas(v); + if(x == 0 || x == 0xCAFEBABE) + return x; + fprint(2, "%d: tas %p got %ux\n", getpid(), v, x); + abort(); +} + +int +canlock(Lock *l) +{ + return !_xtas(&l->val); +} + +void +unlock(Lock *l) +{ + l->val = 0; +} + +void +lock(Lock *lk) +{ + int i; + + /* once fast */ + if(!_xtas(&lk->val)) + return; + /* a thousand times pretty fast */ + for(i=0; i<1000; i++){ + if(!_xtas(&lk->val)) + return; + sched_yield(); + } + /* now nice and slow */ + for(i=0; i<1000; i++){ + if(!_xtas(&lk->val)) + return; + usleep(100*1000); + } + /* take your time */ + while(_xtas(&lk->val)) + usleep(1000*1000); +} -- cgit v1.2.3