/*

  silcwin32mutex.c

  Author: Pekka Riikonen <priikone@silcnet.org>

  Copyright (C) 2001 - 2005 Pekka Riikonen

  The contents of this file are subject to one of the Licenses specified 
  in the COPYING file;  You may not use this file except in compliance 
  with the License.

  The software distributed under the License is distributed on an "AS IS"
  basis, in the hope that it will be useful, but WITHOUT WARRANTY OF ANY
  KIND, either expressed or implied.  See the COPYING file for more
  information.

*/
/* $Id: silcwin32mutex.c,v 1.3.2.3 2005/05/05 18:37:21 priikone Exp $ */

#include "silcincludes.h"

/* SILC Mutex structure */
struct SilcMutexStruct {
#ifdef SILC_THREADS
  CRITICAL_SECTION mutex;
  BOOL locked;
#else
  void *tmp;
#endif /* SILC_THREADS */
};

bool silc_mutex_alloc(SilcMutex *mutex)
{
#ifdef SILC_THREADS
  *mutex = silc_calloc(1, sizeof(**mutex));
  InitializeCriticalSection(&((*mutex)->mutex));
#endif /* SILC_THREADS */
  return TRUE;
}

void silc_mutex_free(SilcMutex mutex)
{
#ifdef SILC_THREADS
  if (mutex) {
    DeleteCriticalSection(&mutex->mutex);
    silc_free(mutex);
  }
#endif /* SILC_THREADS */
}

void silc_mutex_lock(SilcMutex mutex)
{
#ifdef SILC_THREADS
  if (mutex) {
    EnterCriticalSection(&mutex->mutex);
    assert(mutex->locked == FALSE);
    mutex->locked = TRUE;
  }
#endif /* SILC_THREADS */
}

void silc_mutex_unlock(SilcMutex mutex)
{
#ifdef SILC_THREADS
  if (mutex) {
    assert(mutex->locked == TRUE);
    mutex->locked = FALSE;
    LeaveCriticalSection(&mutex->mutex);
  }
#endif /* SILC_THREADS */
}
