Home > Back-end >  std::thread in a loop results in incorrect results
std::thread in a loop results in incorrect results

Time:10-09

I am working on a program that runs in a for loop. Since the arguments and outputs for each call is unique I though I could parallelize the calls within the loop. However this doesn't work correctly. Following is an example program that illustrates this issue

#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;
}

The output of this run is as follows

 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

I do understand the calls will be out of sync. However the index and the values of emod and prat corresponding to that index don't match either. The correct values should be

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

Wondering what I am missing. Any help is appreciated

CodePudding user response:

Dont pass the counter by reference, as when it increments in main, it will increment in the thread as well. Pass it by value.

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