I would like to create a wrapper for a Boost conditional variable:
class Cond_wrap
{
private:
boost::condition_variable cond;
boost::mutex mutex;
bool work_to_do;
public:
Cond_wrap()
{
work_to_do = false;
}
void notify_all()
{
boost::mutex::scoped_lock lock(mutex);
work_to_do = true;
cond.notify_all();
}
void wait()
{
boost::mutex::scoped_lock lock(mutex);
while(!work_to_do)
{
cond.wait(lock);
work_to_do = false;
}
}
bool timed_wait(unsigned int timeout)
{
boost::mutex::scoped_lock lock(mutex);
if(!work_to_do)
{
if(cond.timed_wait(lock, boost::chrono::milliseonds(timeout)))
{
work_to_do = false;
return true;
}
else
{
return false;
}
}
else
{
return false;
}
};
Cond_wrap condition_wrap;
void worker_func()
{
{
condition_wrap.notify_all();
}
std::cout << "After notify" << std::endl;
}
int main()
{
boost::thread work(worker_func);
work.detach();
{
boost::this_thread::sleep_for(boost::chrono::milliseonds(500));
condition_wrap.wait();
//there is work to do
}
return 0;
}
What is the main goal of that wrapper? I would like to avoid a situation in which a condition will be notified before I call waiter. Regarding this, I want to provide a help variable bool which should remember if a condition was previously set.
Small example of what I mean:
boost::condition_variable cond;
boost::mutex mutex;
void worker_func()
{
cond.notify_all();
std::cout << "After notify" << std::endl;
}
void main()
{
boost::mutex::soped_lock lock(mutex);
boost::thread work(worker_func);
boost::this_thread::sleep_for(boost::chrono::milliseonds(500));
cond.wait(lock); // here is deadlock
}
The wrapper is also provides an easier way of using a Boost conditional variable.