【folly】folly::atomic_shared_ptr
folly::atomic_shared_ptr
folly::atomic_shared_ptr<T> 是 Facebook 的 Folly 库提供的一个 线程安全的 std::shared_ptr 原子封装器。它弥补了标准 C++ 中 std::shared_ptr 不能直接进行原子读写的缺陷(直到 C++20 引入 std::atomic<std::shared_ptr<T>>)。在更早的 C++ 标准下,或者在更强的性能/兼容性要求下,folly::atomic_shared_ptr 是非常实用的。
#include <folly/synchronization/AtomicSharedPtr.h>
#include <memory>
#include <thread>
#include <iostream>
struct MyObj {
int x;
MyObj(int v) : x(v) {}
};
folly::atomic_shared_ptr<MyObj> g_ptr;
void reader() {
for (int i = 0; i < 10; ++i) {
auto ptr = g_ptr.load(); // 原子加载
if (ptr) {
std::cout << "Reader sees: " << ptr->x << std::endl;
}
}
}
void writer() {
for (int i = 0; i < 10; ++i) {
g_ptr.store(std::make_shared<MyObj>(i)); // 原子替换
}
}
int main() {
std::thread t1(reader);
std::thread t2(writer);
t1.join();
t2.join();
}

浙公网安备 33010602011771号