我试图在自己的线程中运行成员函数并遵循此帖子,但是在该示例中,线程在同一函数中启动和完成。您如何维护对线程的引用,以加入单独的成员函数(例如destructor)?我已经尝试过:
class foo
{
foo();
~foo();
volatile sig_atomic_t m_run_thread = true;
std::thread &m_read_thread;
void read_thread();
}
foo::foo():m_read_thread(std::thread(&foo::read_thread, this))
{
}
foo::~foo()
{
m_run_thread = false;
m_read_thread.join();
}
void foo::read_thread()
{
while(m_run_thread)
{
//do something cool
}
}
int main()
{
foo bar;
//do other stuff
}
编译器给我一个错误:错误:从类型的" std :: thread"类型的" std :: thread&"类型的非const引用的初始化。这是因为我试图将临时性绑定到参考。这种解决此问题的最佳方法是什么?
foo::foo():m_read_thread(std::thread(&foo::read_thread, this))
无法工作,因为 std::thread(&foo::read_thread, this)
是临时值,临时性不能绑定到非const lvalue参考。
说没有理由使线程成员成为参考。您可以简单地拥有一个std::thread
成员,例如std::thread m_read_thread;
,然后在构造函数中您会像
foo::foo() : m_read_thread(std::thread(&foo::read_thread, this))