multithreading - 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 ) );
解决方案
您的示例代码中唯一明确缺少使其编译的是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();
}
}
推荐阅读
- javascript - 从所有数组MongoDB中拉出一个项目
- c# - Xamarin Forms ListView 分组内容不绑定
- reactjs - 无法解决“TypeError:firebase__WEBPACK_IMPORTED_MODULE_1__.default.createUserWithEmailAndPassword 不是函数”错误
- node.js - Elasticsearch NodeJS 客户端将无法访问的节点显示为活动的
- arrays - 是否可以创建一个 Excel 数组公式,其中每个元素 n 是另一个数组的前 n 个元素的总和?
- scikit-learn - 分类 - 在给定变量的情况下定义 K 倍拆分
- amazon-web-services - AWS PrivateLink 终端节点 IP 地址可以更改吗?
- javascript - 如何使用 Azure CI/CD Pipeline 将 Ember.js 应用程序正确部署到 Azure 应用程序服务?
- excel - 在 Excel 中,有没有办法使用“索引匹配匹配”在多个工作表上查找一个值,然后粘贴所需工作表中的值?
- python - 尝试使用 PySpark 读取 MySQL 表时出错