实现上述的同步,使用了两个事件(Event)和两个互斥量(Mutex),分别为:
/** Events 事件 */ HANDLE m_heventUnpaused; //暂停 HANDLE m_heventThreadDead; //停止 /** Mutexes 互斥量*/ HANDLE m_hThreadRunningMutex; //运行 HANDLE m_hGrabbingPauseFlagMutex; //暂停 还有两个布尔变量,分别用来控制运行于暂停,是上面的两个互斥量保护的资源,如下: bool m_bPaused; //暂停 bool m_bThreadRun; //运行先把上面各个变量初始化一下:
m_heventUnpaused = CreateEvent( NULL, FALSE, FALSE, NULL ); //将暂停事件初始化为无信号状态 m_heventThreadDead = CreateEvent( NULL, FALSE, FALSE, NULL ); m_hThreadRunningMutex = ::CreateMutex( NULL, FALSE, NULL ); m_hGrabbingPauseFlagMutex = ::CreateMutex( NULL, FALSE, NULL ); //将暂停互斥量初始化为无线程拥有该互斥量状态 m_bPaused = false; m_bThreadRun = false;
BOOL threadFlag() //读操作 { BOOL returnValue = false; DWORD dwRet = ::WaitForSingleObject( m_hThreadRunningMutex, 1000 ); if( dwRet == WAIT_OBJECT_0 ) { returnValue = m_bThreadRun; } ::ReleaseMutex( m_hThreadRunningMutex ); return returnValue; }; void setThreadRunningFlag( bool trueOrFalse ) //写操作 { DWORD dwRet = ::WaitForSingleObject( m_hThreadRunningMutex, 5000 ); if( dwRet == WAIT_OBJECT_0 ) { m_bThreadRun = trueOrFalse; } ::ReleaseMutex( m_hThreadRunningMutex ); return; };
UINT threadBFunction(void* pParam) { while( threadFlag() ) { ... } ... }
BOOL grabbingPaused() { BOOL returnValue = false; DWORD dwRet = ::WaitForSingleObject( m_hGrabbingPauseFlagMutex, 5000 ); if( dwRet == WAIT_OBJECT_0 ) { returnValue = m_bPaused; } ::ReleaseMutex( m_hGrabbingPauseFlagMutex ); return returnValue; }; void setGrabbingPausedFlag( bool trueOrFalse ) { DWORD dwRet = ::WaitForSingleObject( m_hGrabbingPauseFlagMutex, 1000 ); if( dwRet == WAIT_OBJECT_0 ) { m_bPaused = trueOrFalse; } ::ReleaseMutex( m_hGrabbingPauseFlagMutex ); return; };
UINT threadBFunction(void* pParam) { while( threadFlag() ) { if( grabbingPaused() ) { DWORD dw = WaitForSingleObject( m_heventUnpaused, INFINITE ); ASSERT( dw == WAIT_OBJECT_0 ); } ... //计算处理 } ... }
bool PauseCapture() { if ( grabbingPaused() ) { setGrabbingPausedFlag ( false ); } else { setGrabbingPausedFlag ( true ); } if( !grabbingPaused() ) { SetEvent( m_heventUnpaused ); } return true; }
bool StopCapture( void) { // Inform the grab thread to quit if ( threadFlag() ) { setThreadRunningFlag ( false ); DWORD dwRet = WaitForSingleObject( m_heventThreadDead, 5000 ); ASSERT( dwRet == WAIT_OBJECT_0 ); } ... }
UINT threadBFunction(void* pParam) { while( threadFlag() ) { if( grabbingPaused() ) { DWORD dw = WaitForSingleObject( m_heventUnpaused, INFINITE ); ASSERT( dw == WAIT_OBJECT_0 ); } ... //计算处理 } SetEvent( m_heventThreadDead ); }