I have posted on this topic before, but as yet I have not had much luck. I put it down down to a bad question on my part. This time I have made a short compilable example that displays the bad behavior i’m trying to avoid. I hope this is appreciated.
The problem is two (or more) threads are set to run the same process and their “id’s” determine which part of the variable data they operate on. Currently both threads will update the counter.
The current output looks like this,
tid = 0, var[tid] = 0
tid = 0, var[tid] = 1
tid = 0, var[tid] = 2
tid = 0, var[tid] = 3
tid = 0, var[tid] = 4
tid = 0, var[tid] = 5
tid = 0, var[tid] = 6
tid = 0, var[tid] = 7
tid = 0, var[tid] = 8
tid = 0, var[tid] = 9
tid = 1, var[tid] = 0
Press any key to continue . . .
The desired output should be like this…
tid = 0, var[tid] = 0
tid = 1, var[tid] = 0
tid = 0, var[tid] = 1
tid = 1, var[tid] = 1
tid = 0, var[tid] = 2
tid = 1, var[tid] = 2
tid = 0, var[tid] = 3
tid = 1, var[tid] = 3 etc.
Any guidance here would be greatly appreciated.
EDIT: Ive updated the answer with code that works as intended.
[Note that efficiency is important here, I want to complete the process as quickly as possible]
#include <iostream>
#include <boost/thread.hpp>
int var[2];
int mT;
int mTotalSamples;
boost::mutex mCountMutex;
boost::thread *threadMap[2];
using namespace std;
void process()
{
int tid = 1;
// sleep for 1 seconds - just to make sure threadMap
// has been assigned (only ncessary for this demo).
boost::this_thread::sleep(boost::posix_time::seconds(1));
if (threadMap[0]->get_id() == boost::this_thread::get_id()){ tid = 0;}
while ( mT < mTotalSamples )
{
// perform processing
var[tid] = mT;
// processing complete
mCountMutex.lock(); // (a thread waits to aquire mutex)
cout << "tid = " << tid << ", var[tid] = " << var[tid] << endl;
mT++; // How to stop both threads incrementing this?
mCountMutex.unlock();
}
}
int main()
{
boost::thread_group threads;
mT = 0;
mTotalSamples = 10;
threadMap[0] = threads.create_thread( boost::bind(&process) );
threadMap[1] = threads.create_thread( boost::bind(&process) );
threads.join_all();
return 0;
}
Judging from your expected output, you want your threads to synchronize after each update. The
boostlibrary provides boost::barrier which, if you put awaitfor it at the start or end of the while-loop inprocess, should do the trick.