Problems of boost and multithread

For everyone, just starting with C++ or programming at all. Ask newbie questions in this forum!

Moderators: Darobat, RecursiveS, Dante Shamest, Bugdude, Wizard

Problems of boost and multithread

Postby stereoMatching » Tue Sep 27, 2011 4:14 am

below are my codes
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
stereoMatching
 
Posts: 1
Joined: Tue Sep 27, 2011 4:12 am

Return to For Beginners

Who is online

Users browsing this forum: Exabot [Bot] and 4 guests

cron