gpt4 book ai didi

c++ - shared_future 是 condition_variable 的合法替代品吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:41:59 25 4
gpt4 key购买 nike

Josuttis 指出 [“标准库”,第 2 版,第 1003 页]:

Futures allow you to block until data by another thread is provided or another thread is done. However, a future can pass data from one thread to another only once. In fact, a future's major purpose is to deal with return values or exceptions of threads.

另一方面,shared_future<void>可以被多个线程使用,以识别另一个线程何时完成了它的工作。

另外,一般来说,高级并发特性(例如 future s)应该优先于低级并发特性(例如 condition_variable s)。

所以想问一下:有没有一种情况(需要多线程同步)出现shared_future<void>还不够 condition_variable是必不可少的吗?

最佳答案

正如@T.C. 在评论中指出的那样。和@hlt,futures/shared_futures 的使用主要受限,因为它们只能使用一次。所以对于每一个通信任务,你都必须有一个新的future。 Scott Meyers 在以下文章中很好地解释了优缺点:

Item 39: Consider void futures for one-shot eventcommunication.
Scott Meyers: Effective Modern C++ (emphasis mine)

他的结论是,使用 promise/future 对可以避免使用 condidition_variable 的许多问题,提供更好的方法传达一次性事件。付出的代价是您正在为共享状态使用动态分配的内存,更重要的是,对于您想要的每个事件,您必须有一个 promise/future 对进行交流。

关于c++ - shared_future<void> 是 condition_variable 的合法替代品吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50248800/

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