【问题标题】:Why does this C++ thread example not work?为什么这个 C++ 线程示例不起作用?
【发布时间】:2016-11-26 06:42:02
【问题描述】:

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

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);

【问题讨论】:

  • 没有#include 列表。在main() 中,没有a。没有btemp->C; 毫无意义。同样,temp->E; t 不是“可调用的”,即使是,A 也是一种类型,因此作为参数没有意义。爬行,走路,然后跑。这些错误都与线程无关。
  • std::thread 类型的对象没有operator(),因此表达式t(...) 无效。试试std::thread t(A::d, a);
  • 我已经抽象了所有这些细节以简化问题
  • @Charlie 效果很好。你知道我怎么能有一个线程数组吗?我尝试使用 std::thread my_threads[i](....) 但它说 Bad Array initializer ?请添加您的答案,以便我接受
  • @rajkiran 作为答案添加了其他 cmets 以供您跟进。

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


【解决方案1】:

在这里添加一些东西作为答案。

问题的第一部分是对原始评论的回答。 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&lt;A&gt;。如果你想要一个vector&lt;A*&gt;,那么你不需要在线程构造上做&amp;a

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-10
    • 1970-01-01
    • 2018-06-12
    • 2014-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多