本文介绍了带Lock()和Unlock()的CSemaphore的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有人知道如何通过Lock()和Unlock()方法使用CSemaphore类.
如果有人可以帮助,我真的需要一些代码或示例.
Does any one know how to use the CSemaphore class with the Lock() and Unlock() methods.
I really need some code or examples if anyone can help.
推荐答案
// YourDlg.h
...
class CYourDlg : public CDialog
{
...
// gate control:
static CSemaphore sm_cSemaphore;
// worker threads proc:
static DWORD WINAPI EntertainmentProc(CYourDlg* pcDlg);
...
// some function to be limited by threads access:
void ProcessPyrotechnics();
...
public:
...
};
...
// YourDlg.cpp
...
// gate for two threads only:
/*static*/ CSemaphore CYourDlg::sm_cSemaphore(0, 2);
// loop for possible threads:
/*static*/ DWORD WINAPI CYourDlg::EntertainmentProc(CYourDlg* pcDlg)
{
if (pcDlg) {
while (pcDlg->m_bWorkerRunning) {
// An exception secure object:
CSingleLock cLock(&sm_cSemaphore);
// entry or wait:
cLock.Lock();
// entered, we are one of two allowed threads now:
if (pcDlg->m_bWorkerRunning) {
pcDlg->ProcessPyrotechnics();
}
// done, release the locking:
cLock.Unlock();
...
}
}
return 0;
}
...
HANDLE g_Semaphore;
// Create a semaphore with initial and max.
g_Semaphore = CreateSemaphore( NULL, 4, 4, NULL);
DWORD dwWaitResult;
//take ownership
dwWaitResult = WaitForSingleObject( g_Semaphore, 0L);
// Check the ownership
// Release Semaphore
ReleaseSemaphore( g_Semaphore, 1, NULL) ;
来自Codeproject本身...
初学者的线程同步 [ ^ ]
from Codeproject itself...
Thread Synchronization for Beginners[^]
这篇关于带Lock()和Unlock()的CSemaphore的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!