2017-08-30 56 views
2

有人能告诉我怎样才能运行一个新的线程与成员函数从不同类的对象作为这个类的成员函数?什么即时尝试做我仍然得到错误。从另一个类的成员函数的类中的线程

no match for call to '(std::thread) (void (Boo::*)(), Boo&)'|
no match for call to '(std::thread) (void (Foo::*)(), Foo*)'|

#include <iostream> 
#include <thread> 
using namespace std; 
class Boo 
{ 
public: 
    void run() 
    { 
     while(1){} 
    } 
}; 

class Foo 
{ 
public: 
    void run() 
    { 
     t1(&Boo::run,boo); 
     t2(&Foo::user,this); 
    } 
    void user(); 
    ~Foo(){ 
     t1.join(); 
     t2.join(); 
    } 
private: 
    std::thread t1; 
    std::thread t2; 
    Boo boo; 
}; 
int main() 
{ 
    Foo foo; 
    foo.run(); 
} 
+0

'while(1){}'是UB,参见例如[is-this-infinite-recursion-ub](https://stackoverflow.com/questions/5905155/is-this-infinite-recursion- UB)。 – Jarod42

回答

4

您需要使用operator=建设

以下工作示例(see it in action)后分配线程:

#include <thread> 
#include <iostream> 

class Boo 
{ 
public: 
    void run() 
    { 
     int i = 10; 
     while(i--) 
     { 
      std::cout << "boo\n";; 
     } 
    } 
}; 

class Foo 
{ 
public: 
    void run() 
    { 
     t1 = std::thread(&Boo::run,boo); // threads already default constructed 
     t2 = std::thread(&Foo::user,this); // so need to *assign* them 
    } 

    void user() 
    { 
     int i = 10; 
     while(i--) 
     { 
      std::cout << "foo\n";; 
     } 
    } 

    ~Foo() 
    { 
     t1.join(); 
     t2.join(); 
    } 

private: 
    std::thread t1; 
    std::thread t2; 
    Boo boo; 
}; 

int main() 
{ 
    Foo foo; 
    foo.run(); 
} 
+0

他的错误是因为线程调用的run()和user()方法不接受参数,您的代码是否仍然存在这些错误? – Tyler

+1

不,你错了 - 他试图做的调用是使用'boo'对象执行'Boo'的'run' **成员函数**。也就是说,你同时需要成员函数指针和对象实例 –

+0

好的,谢谢,我误解了线程构造函数的第二个参数。删除了我不正确的答案 – Tyler

相关问题