2016-12-21 71 views
0

我试图在其自己的线程中运行成员函数,并且遵循this post,但是在该示例中,该线程在相同函数中启动并结束。你如何保持对线程的引用来加入单独的成员函数(比如析构函数)?从类型“的std ::线程”的右值的类型“的std ::线程&”的非const引用无效初始化:我已经试过这样:在单独的线程中运行成员函数

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 
} 

编译器虽然给我一个错误:错误。这是因为我试图将临时绑定到引用。什么是解决这个问题的最好方法?

+1

如果它没有编译,你的'm_read_thread'将成为悬空参考'foo'建成后。为什么你有'线程'而不是'线程'成员? – Praetorian

+1

不要将'm_read_thread'作为参考。 –

+0

这不是问题,但'volatile sig_atomic_t'是重要的C语言,用于在主程序和信号处理程序之间进行协调。改为使用'std :: atomic '。 –

回答

3

foo::foo():m_read_thread(std::thread(&foo::read_thread, this))不会工作,因为std::thread(&foo::read_thread, this)是一个临时值,临时值不​​能绑定到非常量左值引用。

这就是说没有理由让线程成员参考。你可以简单的有像std::thread m_read_thread;一个std::thread成员,然后在构造函数中,你会初始化它像

foo::foo() : m_read_thread(std::thread(&foo::read_thread, this)) 
+0

是的,现在我看到它是正确和可笑的简单... –