97 lines
1.5 KiB
C++
97 lines
1.5 KiB
C++
#if (defined(_WIN32)&&!defined(_TRY_POSIX)) /// Windows platform without trying posix.
|
|
|
|
#include "SemaphoreWrapper.h"
|
|
#include <windows.h>
|
|
#include <cstdio>
|
|
|
|
class ProcessSemaphore::impl
|
|
{
|
|
public:
|
|
HANDLE h;
|
|
|
|
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);
|
|
|
|
_p->h=CreateSemaphore(NULL,default_value,default_value,buff);
|
|
|
|
if(_p->h==NULL)
|
|
{
|
|
_p->status=0;
|
|
}
|
|
else
|
|
{
|
|
if(action==1&&(GetLastError()==ERROR_ALREADY_EXISTS))
|
|
{
|
|
CloseHandle(_p->h);
|
|
_p->status=0;
|
|
}
|
|
else
|
|
{
|
|
_p->status=1;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
bool ProcessSemaphore::isReady() const
|
|
{
|
|
return _p&&_p->status==1;
|
|
}
|
|
|
|
int ProcessSemaphore::p()
|
|
{
|
|
DWORD ret=WaitForSingleObject(_p->h,INFINITE);
|
|
if(ret==WAIT_OBJECT_0)
|
|
{
|
|
return 0;
|
|
}
|
|
else if(ret==WAIT_TIMEOUT)
|
|
{
|
|
return -1;
|
|
}
|
|
else
|
|
{
|
|
return -2;
|
|
}
|
|
}
|
|
|
|
int ProcessSemaphore::v()
|
|
{
|
|
ReleaseSemaphore(_p->h,1,NULL);
|
|
return 0;
|
|
}
|
|
|
|
int ProcessSemaphore::wait()
|
|
{
|
|
return p();
|
|
}
|
|
|
|
int ProcessSemaphore::notify()
|
|
{
|
|
return v();
|
|
}
|
|
|
|
ProcessSemaphore::~ProcessSemaphore()
|
|
{
|
|
if(_p)
|
|
{
|
|
if(isReady())
|
|
{
|
|
CloseHandle(_p->h);
|
|
}
|
|
|
|
delete _p;
|
|
}
|
|
}
|
|
|
|
#endif // _WIN32
|