I have the following class method:
myclass::concurFnc(bool changingVar ) {
{
static int i = 0;
++i;
std::cout << "Try Waiting: " << i << std::endl;
std::mutex waitValidMutex;
std::unique_lock<std::mutex> l(waitValidMutex);
mNoOtherThreadDiffCompareVal.wait(l, [this, &changingVar]()
{
mSemMutex.lock();
bool result = false;
if(myclass::staticVar == useCorrectCV)
{
std::cout << "Same var : " << changingVar << i << std::endl;
result = true;
--mSem;
} else if(mSem == 1)
{
std::cout << "Only one in crit section: " << i << std::endl;
--mSem;
myclass::staticVar = changingVar;
result = true;
} else
{
std::cout << "wait: " << i << std::endl;
result = false;
}
std::cout << "Sem is now " << mSem << std::endl;
mSemMutex.unlock();
return result;
});
//DO STUFF
mSemMutex.lock();
++mSem;
std::cout << "In the end sem is: " << mSem << std::endl;
mSemMutex.unlock();
mNoOtherThreadDiffCompareVal.notify_all();
}
//class Member Variables
std::mutex mSemMutex;
std::condition_variable mNoOtherThreadDiffCompareVal;
It should allow to enter the //DO STUFF section if changingVar is the same as for all other callers who are currently inside //DO STUFF (or if its the only one)
The function is called concurrent from functions in boost::threads.
Sometimes it happened that the execution stops because it keeps on waiting although mSem is 1 and notify_all() should have been called
Output before execution stops is:
wait: 3248
Sem is now 0
Try Waiting: 3249
wait: 3249
Sem is now 0
In the end sem is: 1
Only one in crit section: 3249
Sem is now 0
Try Waiting: 3250
wait: 3250
Sem is now 0
In the end sem is: 1
Only one in crit section: 3250
Sem is now 0
In the end sem is: 1
Try Waiting: 3251
Same comp val : 0 of: 3251
Sem is now 0
.In the end sem is: 1
Up to now i could not really reproduce it.
Source: c++