我有以下代码:
class Service {
public:
void start(); // creates thread which creates window and goes to message loop
void stop(); // sends WM_CLOSE message to thread window
private:
HANDLE hMutex;
HANDLE hThread;
HWND hWindow;
};
我希望我的班级执行这样的行为:
Service obj;
obj.start(); // new thread
obj.start(); // do nothing because thread already exists
现在我陷入了互斥锁处理的问题:
void Service::start() {
// check if service is already running
if (/*!!*/) // what should I check: (hThread != NULL)? or (hWindow != NULL)?
return; // no need to create another thread
else
hThread = CreateThread(...);
}
可以控制线程句柄的状态hThread,如果收到信号则意味着线程已终止:
DWORD result = WaitForSingleObject( hThread, 0);
if (result == WAIT_OBJECT_0) {
// the signal is sent and therefore the thread has been terminated
}
else {
// the signal is not sent and hThread is alive
}
请注意,第二个参数是超时,需要将其设置为零以进行非阻塞调用。
您可以查看详细信息参考 https://msdn.microsoft.com/en-us/library/windows/desktop/ms687032(v=vs.85).aspx
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)