Вопрос

how can I block a boost thread and wake it up from another thread? The thread is doing some work, if the work is finished it should block or sleep, if new work is ready the main thread should weake the worker thread. I tried it with a blocking read on a boost ipc message_queue but it was not a performant solution.

Something like this:

void thread()
{
   uint8_t ret=0;
   for(;;) //working loop
   {
      ret=doWork();
      if(ret==WORK_COMPLETE)
      {
         BlockOrSleep();
      }
   }
}

With pthreads I can block on a semaphore but this is not platform independent.

Это было полезно?

Решение

One solution to that problem is a Condition Variable, which is, as the name implies, a way of waiting in a thread until a condition is reached. This requires some mutual co-operation between threads.

From the example in the documentation that I 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();
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top