Merged silc_1_0_branch to trunk.
[silc.git] / lib / silcutil / unix / silcunixmutex.c
1 /*
2
3   silcunixmutex.c
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 2001 - 2005 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 /* $Id$ */
20
21 #include "silcincludes.h"
22
23 /* SILC Mutex structure */
24 struct SilcMutexStruct {
25 #ifdef SILC_THREADS
26   pthread_mutex_t mutex;
27   unsigned int locked : 1;
28 #else
29   void *tmp;
30 #endif /* SILC_THREADS */
31 };
32
33 bool silc_mutex_alloc(SilcMutex *mutex)
34 {
35 #ifdef SILC_THREADS
36   *mutex = silc_calloc(1, sizeof(**mutex));
37   if (*mutex == NULL)
38     return FALSE;
39   pthread_mutex_init(&(*mutex)->mutex, NULL);
40 #endif /* SILC_THREADS */
41   return TRUE;
42 }
43
44 void silc_mutex_free(SilcMutex mutex)
45 {
46 #ifdef SILC_THREADS
47   if (mutex) {
48     pthread_mutex_destroy(&mutex->mutex);
49     silc_free(mutex);
50   }
51 #endif /* SILC_THREADS */
52 }
53
54 void silc_mutex_lock(SilcMutex mutex)
55 {
56 #ifdef SILC_THREADS
57   if (mutex) {
58     if (pthread_mutex_lock(&mutex->mutex))
59       assert(FALSE);
60     assert(mutex->locked == 0);
61     mutex->locked = 1;
62   }
63 #endif /* SILC_THREADS */
64 }
65
66 void silc_mutex_unlock(SilcMutex mutex)
67 {
68 #ifdef SILC_THREADS
69   if (mutex) {
70     assert(mutex->locked == 1);
71     mutex->locked = 0;
72     if (pthread_mutex_unlock(&mutex->mutex))
73       assert(FALSE);
74   }
75 #endif /* SILC_THREADS */
76 }