std::thread 在一个循环中导致不正确的结果

std::thread in a loop results in incorrect results

我正在开发一个 运行 在 for 循环中的程序。由于每个调用的参数和输出都是唯一的,所以我可以在循环中并行化调用。但是,这不能正常工作。以下是说明此问题的示例程序

#include <iostream>
#include <cstdlib>
#include <thread>
#include <mutex>

void subProg1(int& ii, double& emod, double& prat);
using namespace std;


int main()
{
  int imax = 4;
  int ii;
  double emod[4];
  double prat[4];

  std::thread threadpointer[4];

  emod[0] = 10;
  emod[1] = 20;
  emod[2] = 30;
  emod[3] = 40;

  prat[0] = 0.1;
  prat[1] = 0.2;
  prat[2] = 0.3;
  prat[3] = 0.4;


  for (ii=0;ii<imax;ii++) {
    cout<<" In main Program " <<endl;
    cout<<" count = : "<<ii<<" emod = : "<<emod[ii]<<" pRat = : "<<prat[ii]<<endl;
    threadpointer[ii] = std::thread(subProg1,ref(ii),ref(emod[ii]),ref(prat[ii]));
    //threadpointer[ii].join();
  }

  for (ii=0;ii<imax;ii++) {
    threadpointer[ii].join();
  }
    

}

void subProg1(int& ii, double& emod, double& prat)
{
   cout <<" In SubProgram "<<endl;
   cout<<" count = : "<<ii<<" emod = : "<<emod<<" pRat = : "<<prat<<endl;
}

这个运行的输出结果如下

 In main Program
 count = : 0 emod = : 10 pRat = : 0.1
 In SubProgram
 In main Program
 count = : 1 emod = :  count = : 1 emod = : 20 pRat = : 0.2
10 pRat = : 0.1
 In SubProgram
 In main Program
 count = : 2 emod = : 20 pRat = : 0.2
 count = : 2 emod = : 30 pRat = : 0.3
 In SubProgram
 In main Program
 count = : 3 emod = : 40 pRat = : 0.4
 count = : 3 emod = : 30 pRat = :  In SubProgram
 count = : 2 emod = : 40 pRat = : 0.4
0.3

我知道通话会不同步。然而,索引和对应于该索引的 emod 和 prat 的值也不匹配。正确的值应该是

count = :0 emod = : 10 pRat = :0.1
count = :1 emod = : 20 pRat = :0.2
count = :2 emod = : 30 pRat = :0.3
count = :3 emod = : 40 pRat = :0.4

想知道我错过了什么。感谢任何帮助

不要通过引用传递计数器,因为当它在 main 中递增时,它也会在线程中递增。按值传递。

void subProg1(int ii, double& emod, double& prat);