且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++ std :: thread的成员函数

更新时间:2023-11-11 22:34:46

您正在成员函数中运行本地线程。你必须加入它或分离它,因为它是本地的,你必须在函数本身这样做:

You are running a local thread inside a member function. You have to join it or detach it and, since it is local, you have to do this in the function itself:

exampleClass::runThreaded()
{
    std::thread processThread(&exampleClass::completeProcess, this);
    // more stuff
    processThread.join();
} //



我猜你真正想要的是启动一个数据成员线程而不是启动一个本地的。如果你这样做,你仍然必须在某处加入它,例如在析构函数中。在这种情况下,您的方法应该是

I am guessing what you really want is to launch a data member thread instead of launching a local one. If you do this, you still have to join it somewhere, for example in the destructor. In this case, your method should be

exampleClass::runThreaded()
{
    processThread = std::thread(&exampleClass::completeProcess, this);
}

和析构函数

exampleClass::~exampleClass()
{
    processThread.join();
}

processThread 是一个 std :: thread ,而不是一个指针。

and processThread should be an std::thread, not a pointer to one.

有一个 runThreaded 方法作用于线程数据成员,你必须非常小心,在线程加入之前不要调用它多次。在构造函数中启动线程并将其加入析构函数可能更有意义。

Just a note on design: if you are to have a runThreaded method acting on a thread data member, you have to be very careful about not calling it more than once before the thread is joined. It might make more sense to launch the thread in the constructor and join it in the destructor.