Merged from silc_1_0_branch.
[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 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; either version 2 of the License, or
12   (at your option) any later version.
13   
14   This program is distributed in the hope that it will be useful,
15   but WITHOUT ANY WARRANTY; without even the implied warranty of
16   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17   GNU General Public License for more details.
18
19 */
20 /* $Id$ */
21
22 #include "silcincludes.h"
23
24 /* SILC Mutex structure */
25 struct SilcMutexStruct {
26 #ifdef SILC_THREADS
27   pthread_mutex_t mutex;
28   unsigned int locked : 1;
29 #else
30   void *tmp;
31 #endif /* SILC_THREADS */
32 };
33
34 bool silc_mutex_alloc(SilcMutex *mutex)
35 {
36 #ifdef SILC_THREADS
37   *mutex = silc_calloc(1, sizeof(**mutex));
38   if (*mutex == NULL)
39     return FALSE;
40   pthread_mutex_init(&(*mutex)->mutex, NULL);
41 #endif /* SILC_THREADS */
42   return TRUE;
43 }
44
45 void silc_mutex_free(SilcMutex mutex)
46 {
47 #ifdef SILC_THREADS
48   pthread_mutex_destroy(&mutex->mutex);
49   silc_free(mutex);
50 #endif /* SILC_THREADS */
51 }
52
53 void silc_mutex_lock(SilcMutex mutex)
54 {
55 #ifdef SILC_THREADS
56   if (pthread_mutex_lock(&mutex->mutex))
57     assert(FALSE);
58   assert(mutex->locked == 0);
59   mutex->locked = 1;
60 #endif /* SILC_THREADS */
61 }
62
63 void silc_mutex_unlock(SilcMutex mutex)
64 {
65 #ifdef SILC_THREADS
66   assert(mutex->locked == 1);
67   mutex->locked = 0;
68   if (pthread_mutex_unlock(&mutex->mutex))
69     assert(FALSE);
70 #endif /* SILC_THREADS */
71 }