2016-11-26 38 views
0

我想编译下面的例子,我得到一个错误。下面是代码:为什么此C++线程示例不起作用?

class A { 
    private: 
    //variables 

    public: 
     A(int a,int b){ 
     //assign variables 
     } 
     void C(){ 
     // do something 
     } 
     int D(){ 
     // do something 
     } 
     void E(){ 
     } 
    }; 
int main(){ 
    A* temp = new A(a,b); 
    temp->C; 
    std::thread t; 
    t(&A::D,A); 
    t.join(); 
    temp->E; 
    return 0; 
} 

我收到以下错误,当我编译pthreadstd=c++11标志上面的代码。以下是错误消息:

expected primary-expression before ‘)’ token 
t(&A::D,A); 
+1

没有'#include'列表。在main()中,没有'a'。没有'b'。 'temp-> C;'没有意义。同样对于'temp-> E;''t'不是“可调用的”,即使它是“A”是一种类型,因此作为参数没有意义。抓取,走,然后*运行。这些错误都与线程无关。 – WhozCraig

+0

“std :: thread”类型的对象没有'operator()',所以表达式't(...)'无效。试试'std :: thread t(A :: d,a);'? – Charlie

+0

我已经抽象所有这些细节,以简化问题 – rajkiran

回答

0

在此处添加一些内容作为答案。

问题的第一部分是对原始评论的回答。 std::thread的构造函数使函数运行。还有的线程类中没有额外operator(),所以运行A::d,你需要做的:

std::thread t(A::d, a); 

这将启动线程运行的功能。

关于如何做一个线程数组的问题...因为这是C++,请考虑一个向量。如果你有一个向量AA*你可以做类似的事情。

std::vector<std::thread> threads; 
std::vector<A> as; 
... initialize as, for instance as.push_back(A(...)); ... 
for (auto&& a : as) { threads.emplace_back(A::d, &a); } 
for (auto&& t : threads) { t.join(); } 

注:使用emplace_back时,参数构造函数的参数在向量类型,该类型的不是对象。您也可以使用emplace来设置vector<A>。如果你想要一个vector<A*>,那么你不需要在线程构造上做&a

相关问题