同步机制"数据准备和QUOT;旗? [英] Synchronization Mechanism For "data ready" Flag?

查看:130
本文介绍了同步机制"数据准备和QUOT;旗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑C ++以下伪code:

Consider the following pseudo-code in 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()不会产生相同的数据的能力。

Is there a better way to accomplish this? I was thinking about condition variables, but I need the ability to reset the flag to ensure that back to back calls to RequestData() don't yield the same data.

和往常一样,在此先感谢您的帮助。

As always, thanks in advance for the help.

推荐答案

如果该标志是唯一的你的关心,那么你可以尝试使用原子

If the flag is the only your concern then you might try using 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;
  }
}

然而,在实际的code,你将有推数据和拷贝过来的数据'code件,除非它们被分别同步的。

However, in a real code you will have a race between the 'push data' and 'copy over data' pieces of code, unless they are synchronized separately.

这篇关于同步机制&QUOT;数据准备和QUOT;旗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆