]> mj.ucw.cz Git - libucw.git/blob - ucw/semaphore.h
Merge branch 'dev-free' into dev-lib
[libucw.git] / ucw / semaphore.h
1 /*
2  *      The UCW Library -- POSIX semaphores wrapper
3  *
4  *      (c) 2006 Robert Spalek <robert@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #ifndef _UCW_SEMAPHORE_H
11 #define _UCW_SEMAPHORE_H
12
13 #include <semaphore.h>
14
15 #ifdef CONFIG_DARWIN
16
17 #include <unistd.h>
18 #include <stdio.h>
19 #include <errno.h>
20
21 #include "ucw/fastbuf.h" // For the temp_file_name
22
23 /* In Darwin, sem_init() is unfortunately not implemented and the guide
24  * recommends emulating it using sem_open().  */
25
26 static inline sem_t *
27 sem_alloc(void)
28 {
29   char buf[TEMP_FILE_NAME_LEN];
30   int mode, retry = 10;
31   sem_t *sem;
32   do
33     {
34       temp_file_name(buf, &mode);
35       sem = sem_open(buf, mode | O_CREAT, 0777, 0);
36     }
37   while (sem == (sem_t*) SEM_FAILED && errno == EEXIST && retry --);
38   ASSERT(sem != (sem_t*) SEM_FAILED);
39   return sem;
40 }
41
42 static inline void
43 sem_free(sem_t *sem)
44 {
45   sem_close(sem);
46 }
47
48 #else
49
50 static inline sem_t *
51 sem_alloc(void)
52 {
53   sem_t *sem = xmalloc(sizeof(sem_t));
54   int res = sem_init(sem, 0, 0);
55   ASSERT(!res);
56   return sem;
57 }
58
59 static inline void
60 sem_free(sem_t *sem)
61 {
62   sem_destroy(sem);
63   xfree(sem);
64 }
65
66 #endif
67
68 #endif