You are not logged in.
Hi all,
I'm currently writing a multithreaded modelling program to learn to write parallel things. I'm using C++ and Boost threads.
It's logic is the following: several calculation threads calculate next iteration, one output thread writes results of previous iteration. When it's done, they all must wait when model timer is incremented and a flag is set. To do this, threads call wait() method of tpSystem class object, which returns barrier object address and makes synchronization, if needed. The code looks like the following:
using boost::barrier;
class tpSystem
{
public:
// Some methods
barrier* wait();
private:
// More methods
const int worker_number; // number of calculating threads
barrier* theBarrier;
int counter; // initially set to 0
};
// ...
barrier* tpSystem::wait()
{
if( counter == worker_number )
{
// This part is executed, when the last thread calls me
container->nextStep();
counter = 0;
}
else counter++;
return theBarrier;
}
The problem is that tpSystem::wait() can be called from several threads almost simultaneously. Then counter isn't reset and everything fails.
What can be made to prevent from reenterability problems?
Offline
Wrap the access to counter in a mutex? This should do it:
using boost::barrier;
using boost::mutex;
class tpSystem
{
public:
// Some methods
barrier* wait();
private:
// More methods
const int worker_number; // number of calculating threads
barrier* theBarrier;
int counter; // initially set to 0
mutex counter_mutex;
};
// ...
barrier* tpSystem::wait()
{
mutex::scoped_lock scoped_lock(counter_mutex);
if( counter == worker_number )
{
// This part is executed, when the last thread calls me
container->nextStep();
counter = 0;
}
else counter++;
return theBarrier;
}
Offline
Thanks for solution! But can you explain a bit how it works? I tried to read official Boost manual, but it's quite hard and obscure.
Offline
You know, this is pretty basic, therefore it smells like homework There are some bright folk here who will be glad to help if it is not.
Care to elaborate?
Nothing is too wonderful to be true, if it be consistent with the laws of nature -- Michael Faraday
Sometimes it is the people no one can imagine anything of who do the things no one can imagine. -- Alan Turing
---
How to Ask Questions the Smart Way
Offline