Moved util routines for BeOS from Unix, instead of using them
[silc.git] / lib / silcutil / beos / silcbeosmutex.c
1 /*
2
3   silcbeosmutex.c 
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 2002 Pekka Riikonen
8
9   This program is free software; you can redistribute it and/or modify
10   it under the terms of the GNU General Public License as published by
11   the Free Software Foundation; version 2 of the License.
12
13   This program is distributed in the hope that it will be useful,
14   but WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   GNU General Public License for more details.
17
18 */
19 /* I used Apache's APR code as a reference here. */
20 /* $Id$ */
21
22 #include "silcincludes.h"
23
24 #ifdef SILC_THREADS
25
26 /* SILC Mutex structure */
27 struct SilcMutexStruct {
28   int sema_count;
29   sem_id sema;
30 };
31
32 bool silc_mutex_alloc(SilcMutex *mutex)
33 {
34   int ret;
35
36   *mutex = silc_calloc(1, sizeof(**mutex));
37   if (*mutex == NULL)
38     return FALSE;
39
40   ret = create_sem(0, "SILC_MUTEX");
41   if (ret < B_NO_ERROR) {
42     silc_free(*mutex);
43     return FALSE;
44   }
45
46   (*mutex)->sema_count = 0;
47   (*mutex)->sema = ret;
48
49   return TRUE;
50 }
51
52 void silc_mutex_free(SilcMutex mutex)
53 {
54   delete_sem(mutex->sema);
55   silc_free(mutex);
56 }
57
58 void silc_mutex_lock(SilcMutex mutex)
59 {
60   if (atomic_add(&mutex->sema_count, 1) > 0) {
61     if (acquire_sem(mutex->sema) < B_NO_ERROR)
62       assert(FALSE);
63   }
64 }
65
66 void silc_mutex_unlock(SilcMutex mutex)
67 {
68   if (atomic_add(&mutes->sema_count, -1) > 1) {
69     if (release_sem(mutex->sema) < B_NO_ERROR)
70       assert(FALSE);
71   }
72 }
73
74 #endif /* SILC_THREADS */