c++ - C++线程。为什么总是执行最后一个线程?

标签 c++ multithreading

为什么每次仅执行最后一个线程?我正在尝试将网格划分为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]

这条线是问题的根源。您正在通过引用捕获所有变量,这不是您想要执行的操作。

结果,每个线程使用相同的变量,这也不是您想要的。

您只应通过引用捕获gridthreads,其他变量应按值捕获(“复制”到lambda中)
[start, end, x, &grid, t, nwork, &threads]

另外,您到处访问的grid都不正确:将grid[i][j]更改为grid[j][i]

关于c++ - C++线程。为什么总是执行最后一个线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61563766/

相关文章:

c++ - 从函数返回字符数组

android - OpenCV,安卓 : cannot edit pixels of camera frame converted to HLS colorspace

c# - 使用线程的 ASP.NET MVC 自定义验证

c++ - 如何让 MPI_Send 让处理器按顺序发送而不是随机发送?

android - 60Hz 的动画是如何工作的?

c++ - Direct3D9 无法让垂直 fov 相机工作

c++ - 如何使 float 表现为 double?

c++ - 在 linux ubuntu 上运行 Qt 5 中的 qwt 示例

.net - 有没有人写过线程安全的BindingList <T>?

c++ - 为什么不能在 Boost.Test 测试用例中创建线程?