liveBook · Manning

Thread-safe data structure

As explained in C++ Concurrency in Action, Second Edition

A data structure that permits supported concurrent operations while preserving its invariants.

A thread-safe data structure supports particular concurrent operations while keeping its invariants intact: threads see self-consistent state, and data is neither lost nor corrupted. Safety depends on the operations involved; some may overlap, while others require exclusive access. section 6.1

Safety alone does not provide much concurrency. A mutex prevents simultaneous access to protected data, making threads take turns. Smaller protected regions reduce serialization and leave more opportunity for operations to proceed concurrently. section 6.1

Design decisions should consider which operations can overlap:

  • Allow concurrent reads where possible, while requiring exclusive access for modifications; std::shared_mutex can support this pattern. section 6.1.1
  • Permit different operations to proceed concurrently when safe, while serializing threads that attempt the same operation. section 6.1.1
  • Lock-based designs use mutexes and locks to protect data; designs without locks are a separate approach. section 6.1.1

How C++ Concurrency in Action, Second Edition covers it

How deep it goes
Explains operation-dependent safety, serialization, and lock-based design choices, while deferring designs without locks.
Examples
Contrasts concurrent reads with exclusive modifications and distinguishes different operations from simultaneous attempts at the same operation.
What you can do after
Evaluate designs by identifying which operations can overlap and where exclusive access or serialization is required.
How it connects
Connects thread safety to mutexes, locks, serialization, mutual exclusion, and shared mutexes.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C++ Concurrency in Action, Second Edition. The section links point to the parts of the book it draws on.