Click here to Skip to main content
15,886,806 members
Please Sign up or sign in to vote.
2.20/5 (5 votes)
See more:
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.
Posted
Updated 28-Mar-10 12:45pm
v2

Is Google[^] down today? or you just don't know how to use it?
 
Share this answer
 
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;
}
...
 
Share this answer
 
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) ;


from Codeproject itself...
Thread Synchronization for Beginners[^]
 
Share this answer
 
v2
hi you can check this link : Thread Synchronization for Beginners[^]

And if you want you custom semaphore function then specify.. Will give simple semaphore like functions..
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900