← Previous · All Episodes · Next →
Unlocking Concurrent Access with C++20 Atomic Shared Pointers Episode

Unlocking Concurrent Access with C++20 Atomic Shared Pointers

· 01:48

|

The article discusses the introduction of std::atomic<shared_ptr<T>> in C++20, which adds atomicity to standard shared pointers. A normal shared_ptr uses two pointers: one to the actual object and another to a control block containing reference counts and other metadata. The atomic version modifies the control block pointer to utilize the bottom two bits for flags, specifically for a lock mechanism. The implementations from glibc++ and MSVC differ in how they handle locking and waiting for the lock to clear, with one using spinlocks and the other threading notifications. Overall, atomic shared pointers enable safe concurrent access but with some performance trade-offs, especially in mostly-read scenarios.

Key Points:

  • C++20 introduces std::atomic<shared_ptr<T>> for atomic operations on shared pointers.
  • The atomic shared pointer retains the original structure but uses bits of the control block pointer for lock flags.
  • glibc++ employs a spinlock approach, while MSVC uses notification bits with condition variables for waiting.
  • Implications of having internal locking can lead to issues such as priority inversion deadlocks.
  • In read-heavy usage, shared_mutex may offer better performance compared to atomic shared pointers.
  • Clang's libcxx has not yet implemented std::atomic<shared_ptr<T>>.
  • The design choice allows the control block pointer to be aligned, permitting the use of flags without misalignment concerns.
    Link to Article

Subscribe

Listen to jawbreaker.io using one of many popular podcasting apps or directories.

← Previous · All Episodes · Next →