Added SILC Server library.
[silc.git] / lib / silcutil / win32 / silcwin32mutex.c
index 0a186f59610ce0774139a976e5c59247b12be2b1..34db890fe8862e17a5cf193c1a91f02280817aaa 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
 */
 /* $Id$ */
 
-#include "silcincludes.h"
-
-#ifdef SILC_THREADS
+#include "silc.h"
 
 /* SILC Mutex structure */
 struct SilcMutexStruct {
-  HANDLE mutex;
+#ifdef SILC_THREADS
+  CRITICAL_SECTION mutex;
+  BOOL locked;
+#else
+  void *tmp;
+#endif /* SILC_THREADS */
 };
 
-bool silc_mutex_alloc(SilcMutex *mutex)
+SilcBool silc_mutex_alloc(SilcMutex *mutex)
 {
+#ifdef SILC_THREADS
   *mutex = silc_calloc(1, sizeof(**mutex));
-  (*mutex)->mutex = CreateMutex(NULL, FALSE, NULL);
-  if (!(*mutex)->mutex) {
-    silc_free(*mutex);
+  if (!(*mutex))
     return FALSE;
-  }
+  InitializeCriticalSection(&((*mutex)->mutex));
   return TRUE;
+#else
+  return FALSE;
+#endif /* SILC_THREADS */
 }
 
 void silc_mutex_free(SilcMutex mutex)
 {
-  CloseHandle(mutex->mutex);
-  silc_free(mutex);
+#ifdef SILC_THREADS
+  if (mutex) {
+    DeleteCriticalSection(&mutex->mutex);
+    silc_free(mutex);
+  }
+#endif /* SILC_THREADS */
 }
 
 void silc_mutex_lock(SilcMutex mutex)
 {
-  WaitForSingleObject(mutex->mutex, INFINITE);
+#ifdef SILC_THREADS
+  if (mutex) {
+    EnterCriticalSection(&mutex->mutex);
+    assert(mutex->locked == FALSE);
+    mutex->locked = TRUE;
+  }
+#endif /* SILC_THREADS */
 }
 
 void silc_mutex_unlock(SilcMutex mutex)
 {
-  ReleaseMutex(mutex->mutex);
-}
-
+#ifdef SILC_THREADS
+  if (mutex) {
+    assert(mutex->locked == TRUE);
+    mutex->locked = FALSE;
+    LeaveCriticalSection(&mutex->mutex);
+  }
 #endif /* SILC_THREADS */
+}