【发布时间】:2014-05-11 15:09:29
【问题描述】:
我想使用一个管理一个线程(或多个线程)的类。使用组合,这看起来像:
class MyClass{
private:
std::thread mythread;
void _ThreadMain();
public:
MyClass();
// other fields
}
因为std::thread 的默认构造函数没有意义,我需要在MyClass 构造函数中显式调用它:
MyClass::MyClass() : mythread(&MyClass::_ThreadMain,this) {}
但是,在这种情况下,_ThreadMain 方法可能会在构造MyClass 之前执行,从而导致任何奇怪的行为。这显然是不安全的。我该如何解决这个问题?
一个明显的解决方案是使用指向std::thread 的指针,并添加另一个成员函数:
void MyClass::Start(){
// This time mythread is of type std::thread*
mythread = new std::thread(&MyClass::_ThreadMain,this); // One could use std::unique_pointer instead.
}
这将启动该线程。在这种情况下,它会在构造完类之后调用,这确实是安全的。
但是,我想知道是否有任何合理的解决方案可以让我不为此使用指针。感觉应该是有可能的(嘿,在构造类时必须有一种方法来启动线程!),但我想不出任何不会造成麻烦的东西。
我考虑过使用条件变量,以便_ThreadMain 等待构造函数完成其工作,但在构造类之前我不能使用一个,对吧? (如果MyClass 是派生类,这也将无济于事)
【问题讨论】:
-
在
mythread = new std::thread(&MyClass::_ThreadMain,this);处省略new,std::thread是可移动的!考虑std::bind绑定你的类成员函数。 -
你可以让线程等待(在一开始),直到它被告知继续。
-
这里的问题是如果
_ThreadMain方法是虚的,线程会调用错误的函数。我很想看到构造函数做正确事情的解决方案。 -
您使用的是reserved identifier。
标签: c++ multithreading class c++11 initialization