gpt4 book ai didi

c++ - 如何确保对象只有一个线程

转载 作者:太空狗 更新时间:2023-10-29 20:37:49 24 4
gpt4 key购买 nike

我有以下代码:

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;
};

我希望我的类(class)执行这样的行为:

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
}

注意第二个参数是超时时间,非阻塞调用需要设置为0。

详细的可以查看reference

关于c++ - 如何确保对象只有一个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33686786/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com