c++ - std::thread :如何在类主体中将线程声明为普通成员?

标签 c++ multithreading c++11

我希望为 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,则可以轻松调用未定义的行为。相反,请考虑让 Pagestd::vector 作为直接子对象。另外,您不应公开该类的 std::thread 成员。作为一般规则,数据成员应该是 private 以增强封装性,使将来更容易修改类,并防止人们破坏类的所有不变量。

希望这有帮助!

关于c++ - std::thread :如何在类主体中将线程声明为普通成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9266629/

相关文章:

c++ - 静态成员声明 c++11

c++ - 如何解决由内联命名空间中的标识符冲突引起的不明确引用

c++ - 在 main.cpp 之外创建一个类以使用 QtQuick2ApplicationViewer 的正确方法是什么?

java - 我有一个多线程 JAVA 应用程序在具有 N 个内核的 CPU 上运行(在 Linux 上)但是它只使用第 0 个内核而其余内核处于空闲状态

c++ - 我如何将静态 vector 添加到类中

C++队列非锁定

c++ - 在 C++ 中的多个程序之间本地共享数据(如套接字)

c++ - Visual Studio 2013 中的替代标记(不,和等...)

java - 更新两个 JProgressBars

c++ - 获取发出信号的线程的 ID