Merged silc_1_0_branch to trunk.
[crypto.git] / lib / silcutil / unix / silcunixmutex.c
index 6b92ee3286d7a6c56cc79cee37607639e7f61aa4..1336eaeea7d57592db62d2983d3f4dda6efca471 100644 (file)
@@ -4,13 +4,12 @@
 
   Author: Pekka Riikonen <priikone@silcnet.org>
 
-  Copyright (C) 2001 Pekka Riikonen
+  Copyright (C) 2001 - 2005 Pekka Riikonen
 
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
-  the Free Software Foundation; either version 2 of the License, or
-  (at your option) any later version.
-  
+  the Free Software Foundation; version 2 of the License.
+
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
@@ -25,6 +24,7 @@
 struct SilcMutexStruct {
 #ifdef SILC_THREADS
   pthread_mutex_t mutex;
+  unsigned int locked : 1;
 #else
   void *tmp;
 #endif /* SILC_THREADS */
@@ -36,7 +36,6 @@ bool silc_mutex_alloc(SilcMutex *mutex)
   *mutex = silc_calloc(1, sizeof(**mutex));
   if (*mutex == NULL)
     return FALSE;
-
   pthread_mutex_init(&(*mutex)->mutex, NULL);
 #endif /* SILC_THREADS */
   return TRUE;
@@ -45,23 +44,33 @@ bool silc_mutex_alloc(SilcMutex *mutex)
 void silc_mutex_free(SilcMutex mutex)
 {
 #ifdef SILC_THREADS
-  pthread_mutex_destroy(&mutex->mutex);
-  silc_free(mutex);
+  if (mutex) {
+    pthread_mutex_destroy(&mutex->mutex);
+    silc_free(mutex);
+  }
 #endif /* SILC_THREADS */
 }
 
 void silc_mutex_lock(SilcMutex mutex)
 {
 #ifdef SILC_THREADS
-  if (pthread_mutex_lock(&mutex->mutex))
-    assert(FALSE);
+  if (mutex) {
+    if (pthread_mutex_lock(&mutex->mutex))
+      assert(FALSE);
+    assert(mutex->locked == 0);
+    mutex->locked = 1;
+  }
 #endif /* SILC_THREADS */
 }
 
 void silc_mutex_unlock(SilcMutex mutex)
 {
 #ifdef SILC_THREADS
-  if (pthread_mutex_unlock(&mutex->mutex))
-    assert(FALSE);
+  if (mutex) {
+    assert(mutex->locked == 1);
+    mutex->locked = 0;
+    if (pthread_mutex_unlock(&mutex->mutex))
+      assert(FALSE);
+  }
 #endif /* SILC_THREADS */
 }