我正在尝试运行这个简单的程序,想知道为什么输出会出错。代码查询硬件并发性,然后尝试启动该数量的线程并执行一些任务。为了完成该任务,我正在写入已调整大小的 vector 的各个元素,但结果仍然出错 -
#include <iostream>
#include <thread>
#include <vector>
#include <functional>
void myMethod(std::vector<int> &v, int threadNumber) {
for(int i = threadNumber - 1; i < v.size(); i+= threadNumber) {
v[i] = threadNumber;
}
}
int main() {
const auto numThread = std::thread::hardware_concurrency();
std::vector<int> vec;
vec.resize(100, 0);
if(numThread < 2) {
std::cout << "Not running\n";
return 0;
}
std::vector<std::thread> vT;
for(int i = 1; i <= numThread; ++i) {
vT.emplace_back(myMethod, std::ref(vec), i);
}
for(auto &t: vT) { t.join(); }
for(const auto &i: vec) {
std::cout << i << ' ';
}
std::cout << std::endl;
}
输出为 -
1 2 3 4 1 3 1 4 3 2 1 4 1 2 3 4 1 3 1 4 3 2 1 4 1 2 3 4 1 3 1 4 3 2 1 4 1 2 3 4 1 3 1 4 3 2 1 4 1 2 3 4 1 3 1 4 3 2 1 4 1 2 3 4 1 3 1 4 3 2 1 4 1 2 3 4 1 3 1 4 3 2 1 4 1 2 3 4 1 3 1 4 3 2 1 4 1 2 3 4
但我期待 - 1 2 3 4 1 2 3 4 ...
最佳答案
在您的 myMethod
函数中,您增加了错误数量的变量 i
-
void myMethod(std::vector<int> &v, int threadNumber) {
for(int i = threadNumber - 1; i < v.size(); i+= threadNumber) {
v[i] = threadNumber;
}
}
实际上应该是-
void myMethod(std::vector<int> &v, int threadNumber) {
const auto numThread = std::thread::hardware_concurrency();
for(int i = threadNumber - 1; i < v.size(); i+= numThread) {
v[i] = threadNumber;
}
}
关于c++ - 根据硬件并发度将任务均分给线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43221741/