Skip to content

Instantly share code, notes, and snippets.

@HeiSir2014
Created April 2, 2018 07:33
Show Gist options
  • Save HeiSir2014/7112b07e5094d2a91f78688631473774 to your computer and use it in GitHub Desktop.
Save HeiSir2014/7112b07e5094d2a91f78688631473774 to your computer and use it in GitHub Desktop.
Windows 同步信号量 SynSemaphore
#include "SynSemaphore.h"
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif // !WIN32_LEAN_AND_MEAN
#include <Windows.h>
CSynSemaphore::CSynSemaphore()
{
m_nHandle = (int)CreateSemaphore(NULL, 0, 1, NULL);
}
CSynSemaphore::~CSynSemaphore()
{
if (m_nHandle)
{
ReleaseSemaphore((HANDLE)m_nHandle, MAXLONG, 0);
CloseHandle((HANDLE)m_nHandle);
m_nHandle = NULL;
}
}
void CSynSemaphore::SetSemaphore()
{
if (m_nHandle)
{
ReleaseSemaphore((HANDLE)m_nHandle, 1, 0);
}
}
void CSynSemaphore::WaitSemaphore()
{
if (m_nHandle)
{
WaitForSingleObject((HANDLE)m_nHandle, INFINITE);
}
}
bool CSynSemaphore::WaitSemaphore(int nTimeOut)
{
if (m_nHandle)
{
auto nResult = WaitForSingleObject((HANDLE)m_nHandle, nTimeOut);
if (nResult == WAIT_TIMEOUT)
{
return false;
}
else if(WAIT_OBJECT_0 == nResult)
{
return true;
}
}
return false;
}
#pragma once
class CSynSemaphore
{
public:
CSynSemaphore();
~CSynSemaphore();
void SetSemaphore();
void WaitSemaphore();
bool WaitSemaphore(int nTimeOut);
private:
int m_nHandle;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment