2016-04-24 50 views
1

我很难在独立线程中调用类成员函数的正确语法。三种选择都不起作用。第1行和第2行引发编译时错误,第3行显示运行时错误。有谁可以告诉我什么是正确的方法。无法在使用C++ 11线程类的单独线程中调用类成员函数

#include <iostream> 
#include <thread> 
#include <mutex> 
using namespace std; 
struct Complex 
{ 
    mutex mx; 
    int i; 
    Complex(int q) : i(q) {} 
    void mul(int x) 
    { 
     lock_guard<mutex> lock(mx); 
     int z = i*x; 
     cout<<z<<endl; 
    } 
    void div(int x) 
    { 
     lock_guard<mutex> lock(mx); 
     int z = i/x; 
     cout<<z<<endl; 
    } 
    void both(int x, int y) 
    { 
     mul(x); 
     div(y); 
    } 
}; 
int main() 
{ 
    //Complex complex(9); 
    //thread t(&Complex::both,&Complex(9),32, 23);  --1 
    //thread t(&Complex::both,complex,32,23);   --2 
    //thread t(&Complex::both,&complex,32,23);   --3 
    return 0; 
} 

回答

4

(1)不起作用,因为表达&Complex(9)是形成不良的 - 你正在试图采取临时的地址和所不允许的。

(2)不起作用,因为std::thread复制其内部的所有参数。 complex的拷贝构造函数被定义为删除,因为它包含std::mutex类型的成员,其copy constructor被删除。

(3)编译正常,但会在运行时失败,因为创建的线程t将在连接之前被销毁。你会首先想要join

std::thread t(&Complex::both, &complex, 32, 32); 
t.join(); 
+0

那么,这是完美的。谢谢您的回答 ! – user3798283

+0

'std :: ref'版本取决于[最近解决的LWG问题](http://cplusplus.github.io/LWG/lwg-defects.html#2219),并且在某些实现中可能无法使用。 –

+0

@ T.C。只是要删除它。没有意识到'ref'的东西太复杂了......谢谢! – Barry

相关问题