lock.c - 9base - revived minimalist port of Plan 9 userland to Unix | |
git clone git://git.suckless.org/9base | |
Log | |
Files | |
Refs | |
README | |
LICENSE | |
--- | |
lock.c (873B) | |
--- | |
1 #include <u.h> | |
2 #include <unistd.h> | |
3 #include <sys/time.h> | |
4 #include <sched.h> | |
5 #include <errno.h> | |
6 #include <libc.h> | |
7 | |
8 static pthread_mutex_t initmutex = PTHREAD_MUTEX_INITIALIZER; | |
9 | |
10 static void | |
11 lockinit(Lock *lk) | |
12 { | |
13 pthread_mutexattr_t attr; | |
14 | |
15 pthread_mutex_lock(&initmutex); | |
16 if(lk->init == 0){ | |
17 pthread_mutexattr_init(&attr); | |
18 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL); | |
19 pthread_mutex_init(&lk->mutex, &attr); | |
20 pthread_mutexattr_destroy(&attr); | |
21 lk->init = 1; | |
22 } | |
23 pthread_mutex_unlock(&initmutex); | |
24 } | |
25 | |
26 void | |
27 lock(Lock *lk) | |
28 { | |
29 if(!lk->init) | |
30 lockinit(lk); | |
31 if(pthread_mutex_lock(&lk->mutex) != 0) | |
32 abort(); | |
33 } | |
34 | |
35 int | |
36 canlock(Lock *lk) | |
37 { | |
38 int r; | |
39 | |
40 if(!lk->init) | |
41 lockinit(lk); | |
42 r = pthread_mutex_trylock(&lk->mutex); | |
43 if(r == 0) | |
44 return 1; | |
45 if(r == EBUSY) | |
46 return 0; | |
47 abort(); | |
48 } | |
49 | |
50 void | |
51 unlock(Lock *lk) | |
52 { | |
53 if(pthread_mutex_unlock(&lk->mutex) != 0) | |
54 abort(); | |
55 } |