gpt4 book ai didi

c++ - 通过线程安全容器传递非线程安全对象

转载 作者:太空狗 更新时间:2023-10-29 20:37:18 25 4
gpt4 key购买 nike

我有一个线程安全的对象队列,它被设计用来模拟在线程链之间移动的工作流水线。在某些情况下,我想将非线程安全对象(例如 std::vector 或其他 STL 容器)作为这些工作项的一部分传递。

现在,如果线程之间有一个共享对象,在确保对象一致性方面存在加载/存储顺序的明显问题。由于线程安全队列确保只有一个线程拥有该对象的所有权,因此多个线程不可能同时尝试修改或读取该对象。我看到的唯一可能的问题是确保先前发出的负载中的内存一致性/由以前的所有者线程存储在对象上。

队列通过创建lock_guard<...>来确保线程安全关于队列操作。不会保证在线程之间移动的对象的内存一致性,因为内存防护和同步将由 lock_guard 处理?

我的一部分想要确保我只在线程之间传递线程安全的对象,但我觉得这种情况应该没有问题。这是真的吗?

最佳答案

The queue ensures thread safety by creating a lock_guard<...> on queue operations. Wouldn't memory consistency of the object being moved between threads be guaranteed since the memory fencing and synchronization would be taken care by the lock_guard?

是的。

Part of me wants to ensure I am only passing thread-safe objects between threads, but I feel like this case there should be no problem. Is this true?

是的。

这就是为什么 volatile 不适用于 C++ 中并发数据访问的原因;它不能解决竞争条件,并且一旦您将并发设备(例如互斥锁)带入战斗以解决该问题,它们也会处理内存一致性问题,因此 volatile 去做。

关于c++ - 通过线程安全容器传递非线程安全对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35230710/

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