shared_ptr_atomic2

shared_ptr_atomic2 (std::atomicstd::shared_ptr)

<memory> 헤더에 정의되어 있어요. std::shared_ptr<T>에 대한 std::atomic의 부분 템플릿 특수화예요. shared_ptr 객체를 원자적으로 조작할 수 있게 해줘요. T는 불완전 타입일 수 있어요. C++20부터 도입됐어요.

출처: cppreference

본문

template< class T >
struct std::atomic<std::shared_ptr<T>>;

(C++20부터)

std::shared_ptr<T>에 대한 std::atomic의 부분 특수화는 사용자가 shared_ptr 객체를 원자적으로 조작할 수 있게 해줘요. T는 불완전 타입일 수 있어요.

여러 실행 스레드가 동기화 없이 같은 std::shared_ptr 객체에 접근하고 그 중 하나라도 shared_ptr의 비-const 멤버 함수를 사용하면, 모든 접근이 std::atomic<std::shared_ptr> 인스턴스를 통해 (또는 C++20부터 deprecated된 독립 함수들로) 수행되지 않는 한 데이터 경쟁이 발생해요.

연관된 use_count 증가는 원자 연산의 일부로 보장돼요. 연관된 use_count 감소는 원자 연산 뒤에 순서가 정해지지만, 그 일부는 아니에요(실패한 CAS에서 expected를 교체할 때의 use_count 변경 제외). 연관된 삭제·해제는 원자 갱신 단계 뒤에 순서가 정해지고 원자 연산의 일부가 아니에요.

shared_ptr의 제어 블록은 스레드 안전하므로, 서로 다른 비-원자 std::shared_ptr 객체는 내부적으로 같은 제어 블록을 공유하더라도 operator=이나 reset 같은 가변 연산으로 여러 스레드가 동시에 접근할 수 있어요.

중첩 타입

  • value_type: std::shared_ptr<T>

멤버 함수

이 특수화는 특수화되지 않은 std::atomic 함수를 모두 제공하고, 추가 멤버 함수는 없어요. 주요 함수는 is_lock_free, store, load, exchange, compare_exchange_weak/strong, wait, notify_one, notify_all, is_always_lock_free 등이에요.

주의 (Notes)

기능 테스트 매크로는 __cpp_lib_atomic_shared_ptr(C++20)과 __cpp_lib_constexpr_memory(C++26)이에요.

결함 보고 (Defect reports)

LWG 3661은 atomic<shared_ptr<T>>가 널로부터 상수 초기화될 수 없던 것을 가능하게 고쳤고, LWG 3893은 nullptr_t 대입성 문제를 복원했어요.

shared_ptr를 다중 스레드에서 공유하고 원자적으로 갱신해야 할 때 std::atomic<std::shared_ptr<T>>를 사용해요. 기존의 전역 std::atomic_load/atomic_store 함수 계열을 대체해요.

std::atomic<std::shared_ptr<Widget>> g_widget;
std::shared_ptr<Widget> cur = g_widget.load();
g_widget.store(std::make_shared<Widget>());

더 알아보기 (Learn more)

cppreference