gpt4 book ai didi

c++ - "data ready"标志的同步机制?

转载 作者:行者123 更新时间:2023-11-30 02:36:19 26 4
gpt4 key购买 nike

考虑以下 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() 的背靠背调用不会产生相同的数据。

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

最佳答案

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

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

关于c++ - "data ready"标志的同步机制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32951533/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com