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

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

本文介绍了如何确保对象只有一个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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

我希望我的班级表现出这样的行为:

I want my class to perform behaviour like this:

Service obj;
obj.start(); // new thread
obj.start(); // do nothing because thread already exists

现在,我遇到了由互斥锁覆盖哪个句柄的问题:

Now I'm stuck on question which handle to cover by mutex:

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是否是有效的句柄:

You can simply check if hThread is a valid handle or not:

if (hThread != NULL)
    return;
else
    hThread = CreateThread(...);

CreateThread 返回有效的句柄,因此请确保在调用CreateThread之后进行适当的处​​理.您还需要确保在构造函数中将hThread初始化为NULL:

CreateThread returns a valid handle if the thread is successfully created, so make sure you have proper handling after your call to CreateThread. You will also need to ensure you initialise hThread to NULL in your constructor:

Service::Service() : hMutex(NULL), hThread(NULL) etc...
{
}

如果您使用的是 std::thread ,则只需检查是否该线程为 joinable :

If you were using std::thread instead, you could simply check whether the thread was joinable:

class Service
{
public:
    void start();
private:
    std::thread thread;
};
Service::start()
{
    if (thread.joinable())
        return;
}

这篇关于如何确保对象只有一个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 10:21