[英]How to ensure object has only one thread
我有以下代碼:
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
}
請注意,第二個參數是超時,需要將非阻塞調用設置為零。
您可以查看詳細參考
您只需檢查hThread
是否是有效句柄:
if (hThread != NULL)
return;
else
hThread = CreateThread(...);
如果成功創建了線程, CreateThread
將返回有效句柄,因此請確保在調用CreateThread
后正確處理。 您還需要確保在構造函數中將hThread
初始化為NULL
:
Service::Service() : hMutex(NULL), hThread(NULL) etc...
{
}
如果您使用的是std::thread
,則只需檢查該線程是否joinable
:
class Service
{
public:
void start();
private:
std::thread thread;
};
Service::start()
{
if (thread.joinable())
return;
}
我將采用RAII方式並在構造函數中創建線程並在析構函數中關閉它。 主要的優點是你不能忘記關閉服務(即使有異常),並且構造函數一次只能被一個線程調用一次。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.