I am doing a multhread C++ boost on Linux.
The following program still have race conditions even though I tried to use locks.
The result is 8 or 9 or 5 . it should NOT happen.
#include <iostream>
#include <boost/bind.hpp>
#include <boost/threadpool.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread.hpp>
boost::mutex myMutex ;
int g = 0 ;
void f()
{
//myMutex.lock();
{
boost::mutex::scoped_lock lock(myMutex);
++g;
}
//myMutex.unlock();
return ;
}
const int threadnum = 10;
int main()
{
boost::threadpool::fifo_pool tp(threadnum);
for (int i = 0 ; i < threadnum ; ++i)
tp.schedule(boost::bind(f));
std::cout << g << std::endl ;
return 0 ;
}
Any help will be appreciated.
thanks !
from http://threadpool.sourceforge.net/tutorial/intro.html :
You schedule 10 tasks and then immediately print the result for as many as executed by the time you reach the line
So, while your mutex makes sure threads increment g one at a time, you’re not waiting for them to finish before printing the result.
One way to modify your code is to wait for all tasks in the pool to finish: