24.VC(custom)-辅助线程安全退出( 双Event)

 在日常中,我们经常需要用到辅助线程,那么在程序退出时一定要先保证辅助线程已安全退出,因为在程序销毁时很多资源也被销毁掉了,那么如果这时辅助线程要用到某些资源已不存在了,就可能发生不可预料的后果(一般是程序崩溃)。怎么让辅助线程安全退出呢?直接贴代码吧:

成员变量/线程函数声明:

HANDLE m_hThread; HANDLE m_hThreadEvent[2]; static DWORD WINAPI Thread(LPVOID lpvoid);

OnInitDialog中初始化:

m_hThreadEvent[0] = CreateEvent(NULL, FALSE, FALSE, NULL); // event m_hThreadEvent[1] = CreateEvent(NULL, FALSE, FALSE, NULL); // exit event m_hThread = CreateThread(NULL, 0, Thread, this, 0, NULL);

辅助线程主体:

DWORD WINAPI XXX::Thread(LPVOID lpvoid) { CCCDateTimeDemoDlg *pthis = (CCCDateTimeDemoDlg*)lpvoid; BOOL bContinue = TRUE; DWORD dwRes = 0; while (bContinue) { dwRes = WaitForMultipleObjects(2,pthis->m_hThreadEvent, FALSE, INFINITE); switch (dwRes) { case WAIT_OBJECT_0: { //做你需要的操作 } break; case WAIT_OBJECT_0 + 1: { bContinue = FALSE; } break; default: { bContinue = FALSE; } break; } } return 0; }

退出时设置退出信号,等待

SetEvent(m_hThreadEvent[1]);//设置退出信号量 WaitForSingleObject(m_hThread, INFINITE); CloseHandle(m_hThread); CloseHandle(m_hThreadEvent[0]); CloseHandle(m_hThreadEvent[1]);

原因:m_hThread只有在辅助线程退出后才能变得有信号.

你可能感兴趣的:(thread,object,null,winapi)