为什么这个C ++线程示例不起作用?

时间:2016-11-26 06:42:02

标签: c++ multithreading c++11 pthreads

我正在尝试编译以下示例,但我收到错误。以下是代码:

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 个答案:

答案 0 :(得分:0)

在这里添加一些内容作为答案。

问题的第一部分是对原始评论的回答。 operator()的构造函数使该函数运行。线程类中没有其他A::d,因此要运行std::thread t(A::d, a); ,您需要执行以下操作:

A

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

关于如何做一个线程数组的问题......由于这是c ++,所以请考虑使用向量。如果您有A*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(); } 的向量,则可以执行类似的操作。

vector<A>

注意:使用emplace_back时,参数是向量中类型的构造函数参数,而不是该类型的对象。您还可以使用emplace设置vector<A*>。如果您需要&a,那么您就不需要在线程构建上执行 ByteArrayOutputStream stream= new ByteArrayOutputStream(); stream= stream.toString().replaceAll("&lt;","<");

相关问题