带Lock()和Unlock()的CSemaphore [英] CSemaphore with Lock() and Unlock()

查看:122
本文介绍了带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.

推荐答案

Google [ ^ ]今天下来?还是您不知道如何使用它?
Is Google[^] down today? or you just don''t know how to use it?


一种可能的使用模型:):
A possible usage model :) :
// 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆