#include "StdAfx.h" #include ".\streamthread.h" #include "LWStreamSystem.h" namespace { static DWORD WINAPI _ThreadProc( void* pThis ) { StreamThread* Thread = (StreamThread*)pThis; CoInitialize(NULL); DWORD Ret = Thread->ThreadProc(); // 触发事件,让我们有足够的时间删除对象. SetEvent(Thread->GetEvent()); delete Thread; CoUninitialize(); return Ret; } }; StreamThread::StreamThread(ILWStreamSystem* System) { m_StreamSystem = System; m_Runing = FALSE; m_hEvent = m_hThread = NULL; m_ThreadID = (UINT)-1; } StreamThread::~StreamThread(void) { End(); DeleteCriticalSection(&m_CS); CloseHandle(m_hEvent); CloseHandle(m_hThread); STREAM_LOG("Stream Thread Destroyed.\n"); } void StreamThread::Begin(UINT Priority /*= THREAD_PRIORITY_NORMAL*/, BOOL Suspend/* = FALSE*/) { DWORD CreateFlag = Suspend ? CREATE_SUSPENDED : 0; m_hThread = CreateThread(NULL, 0, _ThreadProc, this, CreateFlag, NULL); if (m_hThread == NULL) return ; InitializeCriticalSection(&m_CS); m_hEvent = CreateEvent(NULL,FALSE,FALSE,NULL); assert(m_hEvent); m_Runing = TRUE; } void StreamThread::End(BOOL Waitflag /*= FALSE*/) { // 锁定,修改RUNING 标记. EnterCriticalSection(&m_CS); m_Runing = FALSE; LeaveCriticalSection(&m_CS); //Resume(); DWORD Stat = WaitForSingleObject(m_hEvent, 30000); if (Stat == WAIT_OBJECT_0) { int foo = 1; } else if (Stat == WAIT_FAILED) { int foo = 1; } STREAM_LOG("Stream thread ended.\n"); } BOOL StreamThread::IsRunning() { return m_Runing; } DWORD StreamThread::ThreadProc() { int isrunning; while (TRUE) { // 更加安全地判断临界的锁定. EnterCriticalSection(&m_CS); isrunning = IsRunning(); LeaveCriticalSection(&m_CS); if (!isrunning) break; try { // m_StreamSystem->Lock(); if (m_StreamSystem && m_StreamSystem->NeedStream()) { ((LWStreamSystem*)m_StreamSystem)->ProcessAllRequests(); } // m_StreamSystem->Unlock(); } catch (...) { ::MessageBox(NULL, /*err.GetText()*/ "处理请求时发生未知错误.", "Fatal Error", MB_OK|MB_ICONEXCLAMATION); // throw err; break; } //#ifndef DEBUG // catch (...) // { // //::MessageBox(NULL, "Unknown error in network system thread", "Fatal Error", // // MB_OK|MB_ICONEXCLAMATION); // // throw 0L; // break; // } //#endif // DEBUG EnterCriticalSection(&m_CS); isrunning = IsRunning(); LeaveCriticalSection(&m_CS); if (!isrunning) break; Suspend(); } return 0; } void StreamThread::Suspend() { if (m_hThread != NULL) { SuspendThread(m_hThread); } } void StreamThread::Resume() { if (m_hThread != NULL) { ResumeThread(m_hThread); } } void StreamThread::SetPriority(UINT Priority) { if (m_hThread) { SetThreadPriority(m_hThread,Priority); } } UINT StreamThread::GetPriority() { return GetThreadPriority(m_hThread); }