我希望为 Page
对象的每个实例都有一个线程。一次只能执行其中一个(只需检查指向当前正在运行的线程的指针是否可连接..)
class Page : public std::vector<Step>
{
// ....
void play();
void start(); // check if no other thread is running. if there is a running thread, return. else join starter
std::thread starter; // std::thread running this->play()
static std::thread* current; // pointer to current running thread
// ...
};
我希望能够启动 Page
对象的 starter
线程。例如这样:
Page x , y , z;
// do some stuff for initialize pages..
x.start();
// do some other work
y.start(); // if x is finished, start y otherwise do nothing
// do some other lengthy work
z.start(); // if x and y are not running, start z
我无法将 started
声明为 Page
的成员。我发现这是因为 std::thread 只能在声明时初始化。 (或类似的东西,因为无法复制线程)
void x()
{
}
//...
std::thread t(x); // this is ok
std::thread r; // this is wrong, but I need this !
r = std::thread(this->y); // no hope
r = std::thread(y); // this is wrong too
最佳答案
您可以使用成员初始值设定项列表将线程初始化为要运行的函数。例如,考虑 Page
的构造函数:
class Page {
public:
Page(); // For example
private:
std::thread toRun;
};
Page::Page() : toRun(/* function to run */) {
/* ... */
}
请注意我们如何使用 Page
构造函数内的初始化列表将 toRun
初始化为应该运行的函数。这样,toRun
就会被初始化,就像您将其声明为局部变量一样
std::string toRun(/* function to run */);
也就是说,我认为您必须在代码中解决两个主要问题。首先,您不应该从 std::vector
或任何标准集合类继承。这些类的析构函数没有标记为 virtual
,这意味着如果您尝试将 Page
视为 std::vector,则可以轻松调用未定义的行为
。相反,请考虑让 Page
将 std::vector
作为直接子对象。另外,您不应公开该类的 std::thread
成员。作为一般规则,数据成员应该是 private
以增强封装性,使将来更容易修改类,并防止人们破坏类的所有不变量。
希望这有帮助!
关于c++ - std::thread :如何在类主体中将线程声明为普通成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9266629/