/*

  silcos2mutex.c 

  Author: Pekka Riikonen <priikone@silcnet.org>

  Copyright (C) 2002 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.

*/
/* I used Apache's APR code as a reference here. */
/* $Id: silcos2mutex.c,v 1.1 2002/02/20 20:53:14 priikone Exp $ */

#include "silcincludes.h"

#ifdef SILC_THREADS

/* SILC Mutex structure */
struct SilcMutexStruct {
  HMTX mutex;
};

bool silc_mutex_alloc(SilcMutex *mutex)
{
  char name[64];

  *mutex = silc_calloc(1, sizeof(**mutex));
  if (*mutex == NULL)
    return FALSE;

  /* Create the lock. Is the name working? :) */
  memset(name, 0, sizeof(name));
  snprintf(name, sizeof(name) - 1, "%p/SEM32/SILC1234$", *mutex);
  if (!DosCreateMutexSem(name, &(*mutex)->mutex, DC_SEM_SHARED, FALSE)) {
    silc_free(*mutex);
    return FALSE;
  }

  return TRUE;
}

void silc_mutex_free(SilcMutex mutex)
{
  DosCloseMutexSem(mutex->mutex);
  silc_free(mutex);
}

void silc_mutex_lock(SilcMutex mutex)
{
  if (!DosRequestMutexSem(mutex->mutex, SEM_INDEFINITE_WAIT))
    assert(FALSE);
}

void silc_mutex_unlock(SilcMutex mutex)
{
  if (!DosReleaseMutexSem(mutex->mutex)
    assert(FALSE);
}

#endif /* SILC_THREADS */
