同步机制用于"数据就绪"旗?

时间:2015-10-05 14:51:02

标签: c++ multithreading boost locking

考虑C ++中的以下伪代码:

// somewhere in common code, properly scoped
boost::mutex data_ready_lock;
bool data_ready;

// Thread 1:
void SomeThreadFunc() {
  // ... push data onto a shared data structure that is properly locked
  data_ready_lock.lock();
  data_ready = true;
  data_ready_lock.unlock();
}

// Thread 2:  (actually a function called from the main() thread)
// Returns the number of bytes written to output_data
size_t RequestData(uint8_t* const output_data) {
  data_ready_lock.lock();
  if (data_ready) {
    // reset the flag, so I don't read out the same data twice
    data_ready = false;
    data_ready_lock.unlock();
    // copy over data, etc.
    return kDataSize;
  } else {
    data_ready_lock.unlock();
    return 0;
  }
}

有没有更好的方法来实现这一目标?我在考虑条件变量,但我需要能够重置标志,以确保对RequestData()的背靠背调用不会产生相同的数据。

一如既往,感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

我不知道你的最终目标是什么,但是使用实际的线程安全队列可以简化你的代码。这是一个:

http://www.boost.org/doc/libs/1_53_0/doc/html/boost/lockfree/queue.html

答案 1 :(得分:1)

如果您只关注该标志,那么您可以尝试使用atomic

// somewhere in common code, properly scoped
boost::atomic< bool > data_ready(false); // can be std::atomic and std::memory_order_* below

// Thread 1:
void SomeThreadFunc() {
  // ... push data onto a shared data structure that is properly locked
  data_ready.store(true, boost::memory_order_release);
}

// Thread 2:  (actually a function called from the main() thread)
// Returns the number of bytes written to output_data
size_t RequestData(uint8_t* const output_data) {
  if (data_ready.exchange(false, boost::memory_order_acquire)) {
    // copy over data, etc.
    return kDataSize;
  } else {
    return 0;
  }
}

但是,在实际代码中,您将在“推送数据”和“复制数据”代码之间进行竞争,除非它们是单独同步的。