如何确保对象只有一个线程
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的方式,在构造函数中创建线程,并在析构函数中关闭它。主要优点是,您不能忘记关闭服务(即使出现异常),并且构造函数一次只能调用一次,而且只能由一个线程调用。
相关文章:
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 在 C++ 中声明 const 对象需要用户定义的默认构造函数.如果我有一个可变成员变量,为什么不呢?
- 有没有办法在同名类 (c++) 中为对象分配一个指针变量
- 我们可以有一个 setter 成员函数作为从 const 对象引用的 const 吗?
- C++是否有一个容器,每个类型最多存储一个对象
- Qt:在一个类中有一个QPainter对象的实例
- 如何让线程等待对象完全破坏?(对象也有一个线程)?
- 让一个名为A的类.传递以下两个对象有什么区别:(a)obj1和(b)obj1()
- 我有一个 Qt 对象的 2d 数组,我已经用值播种了这些对象。如何访问数组中特定对象的值并更改它们?
- 我在代码中有一个错误,错误是:(智能感知:不允许抽象类类型"HourlyWorker"的对象:)
- 类有一个自类型的对象
- 是否有一个函数可以显示我创建的类中的对象到 QTextBrowser 中?
- 在堆栈上有一个对象,而不是在函数的整个生命周期内
- 得到错误"left of '.toString' must have class/struct/union",即使 toString 应该有一个合适的对象
- 我有不同的类,我想用这些类中的对象制作一个向量,然后按值对其进行排序
- 你如何断言一个对象在c++中有一个特定的方法
- 有可能在同一个字符序列上有一个类似函数的宏和一个类似对象的宏吗
- C++如果我有一个对象指针,是在堆栈或堆上分配的方法变量
- 有没有一种方法可以为类的每个对象提供一个boost线程
- JsonCpp - 当有一个 json::Value 对象时,我怎么知道它的键名?