Boost logo

Boost Users :

Subject: Re: [Boost-users] [boost-thread] error in the docs???
From: Steven Watanabe (watanabesj_at_[hidden])
Date: 2009-03-18 20:51:23


AMDG

Ovanes Markarian wrote:
> Did you test it? In my case wait returns when the predicate is false. I use
> an empty circular buffer and call from the same thread this code:
>
> using namespace boost;
>
> scoped_lock lock(mutex_);
> wait_for_free_slots_.wait(lock, bind(&buffer_type::full, buffer_));
> //wait_for_free_slots_ is a condition variable
>
>
> buffer_.push_back(item);
> wait_for_items_.notify_all();
>
> This line returns immediately
> wait_for_free_slots_.wait(lock, bind(&buffer_type::full, buffer_));
> //wait_for_free_slots_ is a condition variable
>
> If you inverse the predicate it blocks forever.
>

Seems to work for me

#include <boost/thread/condition_variable.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/date_time/posix_time/posix_time_duration.hpp>

boost::mutex m;
boost::condition_variable c;

bool value = false;

void set() {
    boost::unique_lock<boost::mutex> l(m);
    value = true;
    c.notify_one();
}

void wait() {
    boost::unique_lock<boost::mutex> l(m);
    c.wait(l, boost::lambda::var(value));
}

int main() {
    boost::thread(wait);
    boost::this_thread::sleep(boost::posix_time::seconds(1));
    set();
}

Look at the definition of wait:

template<typename predicate_type>
void wait(unique_lock<mutex>& m,predicate_type pred)
{
    while(!pred()) wait(m);
}

In Christ,
Steven Watanabe


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net