这种使用增强条件代码有问题吗?

Net*_*zen 1 c++ synchronization boost conditional-statements

这段代码是否会等待生产者内部的互斥体void push(data)

如果是这样,我该如何解决这个问题呢?

boost::mutex access;
boost::condition cond;

// consumer
data read()
{
  boost::mutex::scoped_lock lock(access);

  // this blocks until the data is ready
  cond.wait(lock);

  // queue is ready
  return data_from_queue();
}

// producer
void push(data)
{
  //<--- will a block ever happen here?
  boost::mutex::scoped_lock lock(access);
  // add data to queue

  cond.notify_one();  
}
Run Code Online (Sandbox Code Playgroud)

假设我有一个(;;)循环的线程池,我从这个池中的一个线程调用read().然后我处理它上面的数据.我用一些外部线程调用push().我的问题是,外部线程是否可以阻止其对push(数据)的调用?

Joh*_*ica 8

wait没有notify被召唤就能回来.这被称为虚假唤醒.要处理这个问题,使用条件的代码应始终有一个循环wait来检查预期条件是否真正有效.例如:

queue data_queue;
boost::mutex access;
boost::condition cond;

// consumer
data read()
{
  boost::mutex::scoped_lock lock(access);

  while (queue.is_empty()) {
    // this blocks until the data is ready
    cond.wait(lock);
  }

  // queue is ready
  return data_from_queue();
}

// producer
void push(data)
{
  boost::mutex::scoped_lock lock(access);

  // add data to queue
  queue.push_back(data);

  cond.notify_one();  
}
Run Code Online (Sandbox Code Playgroud)

从概念上讲,"条件"有点误导.相反,你可以把它想象成一个信号.你正在发出另一个或多个线程的信号,但是你没有任何承诺.只是,"嘿,也许有一些准备好的数据,你为什么不去看看?"