首页 > 解决方案 > C++ 向量push_back(): 无法找到创建未命名线程变量的方法

问题描述

创建一个命名线程对我来说效果很好:

void inserter( int iTimes ) {
  for ( int i = 0; i < iTimes; i++ )
      DoOne();
}

int main( int nArg, const char* apszArg[] ) {
  std::thread t1( inserter, 100 );
      :
      :

但是在创建没有名称的线程时,我不知道该怎么做。这会产生无法解析构造函数的错误。我还想知道,一旦它起作用,向量的类型是否是正确的类型,或者thread*我是否需要指定模板参数,如果需要,如何为 1) 函数和 2) 参数列表指定模板参数。

using namespace std;
vector<thread*> apthread;

for ( int i = 0; i < nThreads; i++ )
    apthread.push_back( new thread( inserter, i ) );

标签: multithreadingc++11templates

解决方案


您的示例代码中唯一明确缺少使其编译的是std::https ://godbolt.org/z/3gX_h2

#include <thread>
#include <vector>

void DoOne(){}

void DoMany( int iTimes ) {
    for ( int i = 0; i < iTimes; i++ )
        DoOne();
}

int main(){
    std::vector<std::thread*> apthread;

    const auto nThreads=10;

    for ( int i = 0; i < nThreads; i++ )
        apthread.push_back( new std::thread( DoMany, i ) ); 

    // join all the threads
    for(auto& t: apthread){
        t->join();
    }

}

但是,您永远不应该使用 plain new,并且无论如何都不需要使用动态分配std::thread:它已经是一个句柄,您可以push_back将新的线程对象放入向量中:

#include <thread>
#include <vector>

void DoOne(){}

void DoMany( int iTimes ) {
    for ( int i = 0; i < iTimes; i++ )
        DoOne();
}

int main(){
    std::vector<std::thread> apthread;

    const auto nThreads=10;

    for ( int i = 0; i < nThreads; i++ )
        apthread.push_back(std::thread( DoMany, i ) );    

    // join all the threads
    for(auto& t: apthread){
        t.join();
    }
}

推荐阅读