为什么每次仅执行最后一个线程?我正在尝试将网格划分为N个工作线程,网格的一半始终不可触摸,而其他部分始终以最后创建的1个线程进行。我应该使用数组而不是 vector 吗?锁也无助于解决此问题。
#include <iostream>
#include <unistd.h>
#include <vector>
#include <stdio.h>
#include <cstring>
#include <future>
#include <thread>
#include <pthread.h>
#include <mutex>
using namespace std;
std::mutex m;
int main(int argc, char * argv[]) {
int iterations = atoi(argv[1]), workers = atoi(argv[2]), x = atoi(argv[3]), y = atoi(argv[4]);
vector<vector<int> > grid( x , vector<int> (y, 0));
std::vector<thread> threads(workers);
int start, end, lastworker, nwork;
int chunkSize = y/workers;
for(int t = 0; t < workers; t++){
start = t * chunkSize;
end = start + chunkSize;
nwork = t;
lastworker = workers - 1;
if(lastworker == t){
end = y; nwork = workers - 1;
}
threads[nwork] = thread([&start, &end, &x, &grid, &t, &nwork, &threads] {
cout << " ENTER TO THREAD -> " << threads[nwork].get_id() << endl;
for (int i = start; i < end; ++i)
{
for (int j = 0; j < x; ++j)
{
grid[i][j] = t;
}
}
sleep(2);
});
cout << threads[nwork].get_id() << endl;
}
for(auto& th : threads){
th.join();
}
for (int i = 0; i < y; ++i)
{
for (int j = 0; j < x; ++j)
{
cout << grid[i][j];
}
cout << endl;
}
return(0);
}
最佳答案
[&start, &end, &x, &grid, &t, &nwork, &threads]
这条线是问题的根源。您正在通过引用捕获所有变量,这不是您想要执行的操作。
结果,每个线程使用相同的变量,这也不是您想要的。
您只应通过引用捕获
grid
和threads
,其他变量应按值捕获(“复制”到lambda中)[start, end, x, &grid, t, nwork, &threads]
另外,您到处访问的
grid
都不正确:将grid[i][j]
更改为grid[j][i]
关于c++ - C++线程。为什么总是执行最后一个线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61563766/