Created
April 2, 2018 07:33
-
-
Save HeiSir2014/7112b07e5094d2a91f78688631473774 to your computer and use it in GitHub Desktop.
Windows 同步信号量 SynSemaphore
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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