- Code: Select all
class equalOut
{
public :
typedef bool result_type;
template<typename T, typename U>
result_type const operator()(T const A, U const B) const
{
std::cout<<A.size()<<", "<<B<<std::endl;
return A.size() == B;
}
};
boost::mutex mut;
std::vector<int> int_vector;
boost::condition_variable int_cond;
void data_preparation_thread()
{
while(int_vector.size() != 10)
{
std::cout<<"front :: 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();
std::cout<<"back :: data preparation thread :: vector size = "<<int_vector.size()<<std::endl;
}
}
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( equalOut(), boost::cref(int_vector), static_cast<size_t>(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();
}
int main()
{
testCondVar();
return 0;
}
The results
front :: data processing thread :: vector size = 0
back :: data processing thread :: vector size = 0
0, 10
front :: data preparation thread :: vector size = 0
front :: data preparation thread :: vector size = 1
front :: data preparation thread :: vector size = 2
front :: data preparation thread :: vector size = 3
front :: data preparation thread :: vector size = 4
front :: data preparation thread :: vector size = 5
front :: data preparation thread :: vector size = 6
front :: data preparation thread :: vector size = 7
front :: data preparation thread :: vector size = 8
front :: data preparation thread :: vector size = 9
10, 10
int_cond = true
my problems is, how could the int_cond.notify_one() only notify the thread t1 one time?
Thank you very much
