c++ - how to block and wake a boost thread? -
how can block boost thread , wake thread? thread doing work, if work finished should block or sleep, if new work ready main thread should weake worker thread. tried blocking read on boost ipc message_queue not performant solution.
something this:
void thread() { uint8_t ret=0; for(;;) //working loop { ret=dowork(); if(ret==work_complete) { blockorsleep(); } } }
with pthreads can block on semaphore not platform independent.
one solution problem condition variable, is, name implies, way of waiting in thread until condition reached. requires mutual co-operation between threads.
from example in documentation linked above:
thread 1:
boost::condition_variable cond; boost::mutex mut; bool data_ready; void process_data(); void wait_for_data_to_process() { boost::unique_lock<boost::mutex> lock(mut); while(!data_ready) { cond.wait(lock); } process_data(); }
thread 2:
void retrieve_data(); void prepare_data(); void prepare_data_for_processing() { retrieve_data(); prepare_data(); { boost::lock_guard<boost::mutex> lock(mut); data_ready=true; } cond.notify_one(); }
Comments
Post a Comment