在这种情况下如何使shared_ptr线程安全?

时间:2015-09-22 12:08:02

标签: c++ boost thread-safety shared-ptr

在boost doc(Shared_ptr doc)中,我看到有一个线程不安全的例子:

//--- Example 4 ---

// thread A
p3 = p2; // reads p2, writes p3

// thread B
// p2 goes out of scope: undefined, the destructor is considered a "write access"

如何处理此案?如何控制p2是否超出范围?

2 个答案:

答案 0 :(得分:1)

同样的规则适用于(几乎)所有类型:如果在另一个线程中销毁它们,则不要在一个线程中访问它们。

同样的解决方案也适用:使用互斥或​​原子操作来同步对线程之间共享的变量的并发访问。

答案 1 :(得分:0)

从C ++ 11开始尝试atomic_store http://www.cplusplus.com/reference/atomic/atomic_store/

示例:

atomic_store(&p3, p2);

更多例子:

// thread A
p3 = atomic_load(&p2);
...

// thread B
atomic_store(&p2, make_shared<Foo>());
相关问题