在boost的shared_ptr实现中,它使用relaxed memory ordering to increment its reference count。这是安全的,因为减量使用获取/释放来确保在释放内存之前线程可以看到以前的任何减量。此方法似乎正确,并出现在Herb Sutters talk on atomics

在libc++的实现中使用full memory barriers

template <class T>
inline T
increment(T& t) _NOEXCEPT
{
    return __sync_add_and_fetch(&t, 1);
}

template <class T>
inline T
decrement(T& t) _NOEXCEPT
{
    return __sync_add_and_fetch(&t, -1);
}

}  // name

有这个决定的原因吗?两者之间在性能或安全性方面有区别吗?

最佳答案

因为当我编写该代码时,编译器(clang)尚未实现C++ 11原子。而且我从来没有回过头来清理它。

这里没有什么微妙的地方。 :-)

关于c++ - 为什么libc++的shared_ptr实现使用完整的内存屏障而不是宽松的内存?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28199212/

10-11 01:52