#ifndef CSEMAPHORE_H
#define CSEMAPHORE_H

#include "glibmm/thread.h"

#if 1
class CSemaphore
{
public:
	typedef size_t resource_type;
	

private:
	Glib::Cond m_cond;
	Glib::Mutex m_sync;
	resource_type m_nResource;
	

public:
	CSemaphore(resource_type resource = resource_type())
		: m_nResource(resource)
	{}
	
	void wait()
	{
		Glib::Mutex::Lock lock(m_sync);
		if (!m_nResource)
			m_cond.wait(m_sync);
		--m_nResource;
	}
	
	void post()
	{
		Glib::Mutex::Lock lock(m_sync);
		if (!m_nResource)
			m_cond.signal();
		++m_nResource;
	}
	
	resource_type getValue()
	{
		Glib::Mutex::Lock lock(m_sync);
		return m_nResource;
	}
	
	void setValue(resource_type resource)
	{
		Glib::Mutex::Lock lock(m_sync);
		m_nResource = resource;
	}
};

#else
#include <semaphore.h>

class CSemaphore
{
	sem_t m_sem;
	

public:
	CSemaphore(size_t resource = 0)
	{
		if(sem_init(&m_sem, 0, resource))
			throw -1;
	}
	
	~CSemaphore()
	{
		sem_destroy(&m_sem);
	}
	

public:
	void wait(void)
	{
		sem_wait(&m_sem);
	}
	
	void post(void)
	{
		sem_post(&m_sem);
	}
	
	bool tryWait(void)
	{
		return (sem_trywait(&m_sem) == 0) ? true : false;
	}

#ifndef __CYGWIN32__
	int getValue(void)
	{
		int value;
		sem_getvalue(&m_sem, &value);
		return value;
	}
#endif
};

#endif

#endif
