/*****************************
File:       lockwrap.CPP
Language:   C++ (header)
Project:    H3DNetworkingUtils
The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/

Software distributed under the License is distributed on an "AS IS"
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
License for the specific language governing rights and limitations
under the License.

The Original Code is H3DNetworkingUtils v1.0.

The Initial Developer of the Original Code is CSIRO.
Portions created by the Initial Developer are Copyright (C) 1009 CSIRO. All Rights Reserved.
Contributor(s):
    Chris Gunn  <Chris.Gunn@csiro.au> <ChrisJGunn@gmail.com>
***************************/

/* Distributed under a BSD type license. See the netwrap COPYRIGHT file */

#include <stdlib.h>
#include <windows.h>

#include "H3DNetworkingUtils/fail.h"

#include "H3DNetworkingUtils/lockwrap.h"

Mutex::Mutex ()
{
  sysMutex = CreateMutex(NULL, 0, NULL);
  FailNull(sysMutex, "Mutex::create");
}

Mutex::~Mutex ()
{
  CloseHandle((HANDLE)sysMutex);
}

void Mutex::lock ()
{
  if (WaitForSingleObject((HANDLE)sysMutex, INFINITE) != WAIT_OBJECT_0)
    Fail("Mutex::lock WaitForSingleObject");
}

void Mutex::unlock ()
{
  if (! ReleaseMutex((HANDLE)sysMutex))
    Fail("Mutex::unlock ReleaseMutex");
}

int Mutex::tryLock ()
{
  int status;

  status = WaitForSingleObject((HANDLE)sysMutex, 0);
  if (status == WAIT_OBJECT_0)
    return 1;
  else if (status == WAIT_TIMEOUT)
    return 0;
  else {
    Fail("Mutex::tryLock WaitForSingleObject");
    return -1; // Keeps compiler happy
  }
}
//****		Semaphores	****

Semaphore::Semaphore (int count)
{
	sysSemaphore = CreateSemaphore(NULL, count, 1, NULL);
}

Semaphore::~Semaphore ()
{
	CloseHandle((HANDLE)sysSemaphore);
}

void Semaphore::signal ()
{
	ReleaseSemaphore((HANDLE)sysSemaphore, 1, NULL);
}

void Semaphore::wait ()
{
	WaitForSingleObject((HANDLE)sysSemaphore, INFINITE);
}

int Semaphore::tryWait ()
{
	int status;
	status = WaitForSingleObject((HANDLE)sysSemaphore, 0);
	if (status == WAIT_OBJECT_0) {
	    return 1;
	} else if (status == WAIT_TIMEOUT) {
	    return 0;
	} else {
	    return 0;
	}
}

