diff options
| author | rsc <devnull@localhost> | 2004-09-17 00:38:29 +0000 |
|---|---|---|
| committer | rsc <devnull@localhost> | 2004-09-17 00:38:29 +0000 |
| commit | 06bb4ed20d855b60e39c1125d8d715ba8892265b (patch) | |
| tree | 8294b537f5b81809671985903e31c4835c41cd04 /src/lib9/lock.c | |
| parent | 984e353160593b20d1e2944e1f2e9ce2117c8490 (diff) | |
| download | plan9port-06bb4ed20d855b60e39c1125d8d715ba8892265b.tar.gz plan9port-06bb4ed20d855b60e39c1125d8d715ba8892265b.zip | |
Rewrite to remove dependence on rendezvous and its bizarre
data structures. Makes it easier to use pthreads too.
Still need to add code for non-pthreads systems.
Just a checkpoint to switch work to another machine.
Diffstat (limited to 'src/lib9/lock.c')
| -rw-r--r-- | src/lib9/lock.c | 70 |
1 files changed, 36 insertions, 34 deletions
diff --git a/src/lib9/lock.c b/src/lib9/lock.c index 80f65b33..eb3ea21d 100644 --- a/src/lib9/lock.c +++ b/src/lib9/lock.c @@ -2,52 +2,54 @@ #include <unistd.h> #include <sys/time.h> #include <sched.h> +#include <errno.h> #include <libc.h> -int _ntas; -static int -_xtas(void *v) +static pthread_mutex_t initmutex = PTHREAD_MUTEX_INITIALIZER; + +static void +lockinit(Lock *lk) { - int x; + pthread_mutexattr_t attr; - _ntas++; - x = _tas(v); - return x; + pthread_mutex_lock(&initmutex); + if(lk->init == 0){ + pthread_mutexattr_init(&attr); + pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL); + pthread_mutex_init(&lk->mutex, &attr); + pthread_mutexattr_destroy(&attr); + lk->init = 1; + } + pthread_mutex_unlock(&initmutex); } -int -canlock(Lock *l) +void +lock(Lock *lk) { - return !_xtas(&l->val); + if(!lk->init) + lockinit(lk); + if(pthread_mutex_lock(&lk->mutex) != 0) + abort(); } -void -unlock(Lock *l) +int +canlock(Lock *lk) { - l->val = 0; + int r; + + if(!lk->init) + lockinit(lk); + r = pthread_mutex_trylock(&lk->mutex); + if(r == 0) + return 1; + if(r == EBUSY) + return 0; + abort(); } void -lock(Lock *lk) +unlock(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); + if(pthread_mutex_unlock(&lk->mutex) != 0) + abort(); } |
