1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
|
#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
|