Add Posix implemention
This commit is contained in:
parent
ba7db6e44a
commit
96a42cdfda
|
@ -4,13 +4,13 @@ class ProcessSemaphore
|
|||
{
|
||||
public:
|
||||
/// action: 0 MustGet 1 MustCreateNew
|
||||
ProcessSemaphore(int key,int action=0,int default_value=1);
|
||||
bool isReady() const;
|
||||
int p(); /// wait
|
||||
int v(); /// notify
|
||||
int wait(); /// p
|
||||
int notify(); /// v
|
||||
~ProcessSemaphore();
|
||||
ProcessSemaphore(int key,int action=0,int default_value=1);
|
||||
bool isReady() const;
|
||||
int p(); /// wait
|
||||
int v(); /// notify
|
||||
int wait(); /// p
|
||||
int notify(); /// v
|
||||
~ProcessSemaphore();
|
||||
private:
|
||||
class impl;
|
||||
impl* _p;
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
#ifndef _WIN32 /// Linux
|
||||
#ifdef __linux__ /// Linux
|
||||
#include "SemaphoreWrapper.h"
|
||||
|
||||
#include <fcntl.h>
|
||||
|
|
89
src/ProcessSemaphore_Posix.cpp
Normal file
89
src/ProcessSemaphore_Posix.cpp
Normal file
|
@ -0,0 +1,89 @@
|
|||
#if (!defined(_WIN32)&&!defined(__linux__)) /// Not Windows or linux... Try posix.
|
||||
|
||||
#include "SemaphoreWrapper.h"
|
||||
#include <fcntl.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/stat.h>
|
||||
#include <semaphore.h>
|
||||
#include <strings.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include "log.h"
|
||||
|
||||
class ProcessSemaphore::impl
|
||||
{
|
||||
public:
|
||||
sem_t* ps;
|
||||
|
||||
int status;
|
||||
};
|
||||
|
||||
ProcessSemaphore::ProcessSemaphore(int key, int action, int default_value) : _p(new impl)
|
||||
{
|
||||
if(_p)
|
||||
{
|
||||
_p->status=0;
|
||||
char buff[64];
|
||||
memset(buff,0,64);
|
||||
sprintf(buff,"LibSemaphoreWrapper_%d",key);
|
||||
|
||||
if(action==1) /// Must Create New.
|
||||
{
|
||||
_p->ps=sem_open(buff,O_CREAT|O_EXCL,0777,default_value);
|
||||
}
|
||||
else /// Must Open
|
||||
{
|
||||
_p->ps=sem_open(buff,O_RDWR,0777,0);
|
||||
}
|
||||
|
||||
if(_p->ps!=SEM_FAILED)
|
||||
{
|
||||
_p->status=2;
|
||||
}
|
||||
else
|
||||
{
|
||||
dprintf("Failed to sem_open. %s\n",strerror(errno));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ProcessSemaphore::~ProcessSemaphore()
|
||||
{
|
||||
if(_p)
|
||||
{
|
||||
/// Notice that sem_close() is used for named semaphore and sem_destroy() is for unnamed semaphore.
|
||||
if(isReady())
|
||||
{
|
||||
sem_close(_p->ps);
|
||||
}
|
||||
|
||||
delete _p;
|
||||
}
|
||||
}
|
||||
|
||||
bool ProcessSemaphore::isReady() const
|
||||
{
|
||||
return _p&&_p->status==2;
|
||||
}
|
||||
|
||||
int ProcessSemaphore::p()
|
||||
{
|
||||
return sem_wait(_p->ps);
|
||||
}
|
||||
|
||||
int ProcessSemaphore::v()
|
||||
{
|
||||
return sem_post(_p->ps);
|
||||
}
|
||||
|
||||
int ProcessSemaphore::wait()
|
||||
{
|
||||
return p();
|
||||
}
|
||||
|
||||
int ProcessSemaphore::notify()
|
||||
{
|
||||
return v();
|
||||
}
|
||||
|
||||
#endif
|
Loading…
Reference in New Issue
Block a user