c++ - 创建线程时如何运行线程主方法?
问题描述
我的线程的主要方法是:
void thrMain(const std::vector<long>& list, std::vector<int>& result,
const int startInd, const int endInd) {
for (int i = startInd; (i < endInd); i++) {
result[i] = countFactors(list[i]);
}
}
我每次使用另一种方法创建一个线程列表:
std::vector<int> getFactorCount(const std::vector<long>& numList, const int thrCount) {
// First allocate the return vector
const int listSize = numList.size();
const int count = (listSize / thrCount) + 1;
std::vector<std::thread> thrList; // List of threads
const std::vector<long> interFac(thrCount); // Intermediate factors
// Store factorial counts
std::vector<int> factCounts(numList.size());
for (int start = 0, thr = 0; (thr < thrCount); thr++, start += count) {
int end = std::max(listSize, (start + count));
thrList.push_back(std::thread(thrMain, std::ref(numList),
std::ref(interFac[thr]), start, end));
}
for (auto& t : thrList) {
t.join();
}
// Return the result back
return factCounts;
}
我遇到的主要问题std::ref(interFac[thr])
是使我的#include <thread>
文件无法正常工作。我曾尝试通过引用取消通行证,但这无济于事。
解决方案
我不知道这interFac
是为了什么,但它看起来像这样:
thrList.push_back(std::thread(thrMain, std::ref(numList),
std::ref(interFac[thr]), start, end));
应该是这样的:
thrList.push_back(std::thread(thrMain, std::ref(numList),
std::ref(factCounts), start, end));
然后它编译。
推荐阅读
- elasticsearch - 无法为暖节点分配索引
- python - 如何获取与 Python 字典中的值对应的键?
- azure - 如何将自定义域名应用于 azure kubernetes 服务 (AKS) 集群?
- c - socket.h 中 accept() 函数的位置
- asp.net-core - 在 AspNetCore MVC Identity 中创建表 AspNetClaims
- javascript - 具有相同原始值的 React 钩子调用 setState 仍然会导致重新渲染
- javascript - 坚持使用线性优化函数优化投资组合权重
- php - 如何在laravel 5.5中的其他pdf文件中插入pdf页面
- java - java map和python字典的比较
- django - 如何在 .xls 文件的 django-import-export 中进行字段验证