plan9port/src/lib9/lock.c

56 lines
873 B
C
Raw Normal View History

2004-03-25 23:03:57 +00:00
#include <u.h>
2003-09-30 17:47:41 +00:00
#include <unistd.h>
2004-04-20 05:11:39 +00:00
#include <sys/time.h>
2003-09-30 17:47:41 +00:00
#include <sched.h>
#include <errno.h>
2004-03-25 23:03:57 +00:00
#include <libc.h>
2003-09-30 17:47:41 +00:00
static pthread_mutex_t initmutex = PTHREAD_MUTEX_INITIALIZER;
static void
lockinit(Lock *lk)
2003-09-30 17:47:41 +00:00
{
pthread_mutexattr_t attr;
2003-09-30 17:47:41 +00:00
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);
2003-09-30 17:47:41 +00:00
}
void
lock(Lock *lk)
2003-09-30 17:47:41 +00:00
{
if(!lk->init)
lockinit(lk);
if(pthread_mutex_lock(&lk->mutex) != 0)
abort();
2003-09-30 17:47:41 +00:00
}
int
canlock(Lock *lk)
2003-09-30 17:47:41 +00:00
{
int r;
if(!lk->init)
lockinit(lk);
r = pthread_mutex_trylock(&lk->mutex);
if(r == 0)
return 1;
if(r == EBUSY)
return 0;
abort();
2003-09-30 17:47:41 +00:00
}
void
unlock(Lock *lk)
2003-09-30 17:47:41 +00:00
{
if(pthread_mutex_unlock(&lk->mutex) != 0)
abort();
2003-09-30 17:47:41 +00:00
}