【发布时间】:2020-10-02 23:16:40
【问题描述】:
我的线程的主要方法是:
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> 文件无法正常工作。我曾尝试通过引用取消通行证,但这无济于事。
【问题讨论】:
-
通常,线程由函数表示。这是线程的“主要”功能。操作系统在调度线程时会运行这个函数。
-
请记住,添加更多线程可能不会使您的程序更高效。最坏的情况是,您的线程被安排在单个内核或处理器上(就像其他程序一样)。所有线程都需要开销来 1) 创建; 2)维护; 3)删除(加入)。更多线程需要更多开销。
-
为了高枕无忧,我强烈建议为每个线程使用单独且不同的函数。代码共享和重入增加了你不想惹的复杂性。
标签: c++ multithreading operating-system