I am learning concurrency programming, I try my best yet can't solve the problem
boost::mutex mut;
std::vector<int> int_vector;
boost::condition_variable int_cond;
void data_preparation_thread()
{
while(int_vector.size() != 10)
{
std::cout<<"data preparation thread :: vector size = "<<int_vector.size()<<std::endl;
boost::lock_guard<boost::mutex> lk(mut);
int_vector.push_back(4);
int_cond.notify_one();
}
}
void data_processing_thread()
{
while(1)
{
std::cout<<"front :: data processing thread :: vector size = "<<int_vector.size()<<std::endl;
boost::unique_lock<boost::mutex> lk(mut);
std::cout<<"back :: data processing thread :: vector size = "<<int_vector.size()<<std::endl;
int_cond.wait(lk, boost::bind( std::equal_to<int>(), int_vector.size(), 10) );
std::cout<<"int_cond = true\n";
lk.unlock();
break;
}
}
void testCondVar()
{
boost::thread t1(data_processing_thread);
boost::thread t2(data_preparation_thread);
t1.join();
t2.join();
}
After I call testCondVar() in main(), the results are
front :: data processing thread :: vector size = 0
back :: data processing thread :: vector size = 0
data preparation thread :: vector size = 0
data preparation thread :: vector size = 1
data preparation thread :: vector size = 2
data preparation thread :: vector size = 3
data preparation thread :: vector size = 4
data preparation thread :: vector size = 5
data preparation thread :: vector size = 6
data preparation thread :: vector size = 7
data preparation thread :: vector size = 8
data preparation thread :: vector size = 9
It never stop, it just stuck at there
How could I solve it?Is this a dead lock?
According to my understanding, if the condition variable is satisfied
The t1 thread should lock the mutex and keep going
What kind of mistakes do I make?
Thank you very much