Concurrency and safety
Concurrency and safety
Short version: the primitives are thread-safe and process-safe, you add no
locks, and the main ring (AdaptiveRing) even picks and changes its own shape
under live traffic. Your one job is to be honest about how many producers and
consumers you have. The rest of this page is the why.
Do I need a Mutex / RwLock / Arc<Mutex<…>>?
No - and you should not add one. Every Shared* ring is already a lock-free
concurrent structure: the synchronization is atomic counters (a producer-owned
head and consumer-owned tail for SPSC; per-slot sequence numbers advanced by
CAS for MPMC). Wrapping a ring in a lock would be three kinds of wrong:
- Redundant - the atomics are the synchronization; the lock guards nothing the ring does not already guard.
- Slower - a lock puts a contended acquire (and a possible syscall) back on the fast path you reached for a ring to avoid.
- Broken across processes - a
std::sync::Mutexlives in process-private memory. It cannot synchronize two processes at all. The ring’s atomics can, because of where they live (next section).
You share the handle directly (&AdaptiveRing / &SharedRing are Sync) or
each thread / process opens the same memory-mapped file. No wrapper type.
Why it is process-safe, not just thread-safe
This is the one non-obvious thing, and it is the whole point. The synchronization atomics live inside the memory-mapped file, not in a process-private struct. Because the file is page-aliased to the same physical pages in every participant, and CPU cache coherence is keyed on physical addresses (not virtual ones), the exact same lock-free protocol that synchronizes two threads also synchronizes two processes - even though they may map the file at different virtual base addresses.
So “thread-safe” and “process-safe” are not two features here; they are one
mechanism. A normal AtomicU64 in a Box is thread-safe but process-private;
moving the atomic into the MMF is what buys the cross-process guarantee. See
The MMF substrate
for the page-alias model.
What you are responsible for: nothing, unless you pin
You do not pick locks, and with the AdaptiveRing you do not pick the ring
shape or a peer ceiling either. The construction counts
(AdaptiveRing::create_anon(max_producers, max_consumers, capacity)) are
sizing hints - how many per-producer backings are pre-allocated up front.
Peers register_producer / register_consumer at runtime from any attached
process; registration past the hint grows the ring on demand (new
backings, published cross-process through the shared peer directory), and the
shape re-morphs to the live counts on every join and leave.
Registration has two ceilings, and only one of them is yours. A ceiling you
pin with with_contract refuses past the count you declared. Above that sits
a substrate-wide ceiling on concurrent peers - PRODUCER_SLOT_CEILING is
4096 and CONSUMER_SLOT_CEILING is 256 - fixed by the size of the shared
peer-directory region. Both refusals arrive as
AdaptiveError::TooManyProducers / TooManyConsumers, so a program that
declares no contract can still see one, at 4096 live producers or 256 live
consumers. Slots are recycled on unregister, so these bound peers alive at
once rather than peers over the ring’s life.
| Ring | Producers x Consumers | Who enforces the count |
|---|---|---|
Typed SPSC pair (Producer / Consumer from SharedRingSpsc::create_anon_pair) | exactly 1 x 1 | the compiler: both handles are Send + !Sync + !Clone, so a second producer cannot be cloned and a single producer cannot be shared across threads |
SharedRing (Vyukov global-FIFO) / composed MPMC | N x N | the CAS protocol, at runtime - any number of producers and consumers race safely |
AdaptiveRing (the main ring) | grows and shrinks with the live peer set | the shared peer directory: cross-process slot claims, on-demand backing growth, automatic shape morphs; refused by a declared with_contract ceiling, or by the directory’s own 4096-producer / 256-consumer concurrent limit |
Pick the typed SPSC pair only when the topology is genuinely one producer and
one consumer forever and you want the type system to weld that in. For anything
else - or when you are not sure - use the AdaptiveRing; it carries no such
constraint and adapts the shape for you.
The AdaptiveRing changes shape while I use it - is that safe?
Yes, including during the change itself, which is the hard part. The
AdaptiveRing
keeps
all four backings (SPSC / MPSC / MPMC / Vyukov) pre-allocated, so a morph
never allocates or tears anything down. A morph is a single atomic re-point:
pin_generation.fetch_add(1)- any caller holding a direct pinned pointer seesis_still_valid() == falseon its next check and re-pins.- the shape being left joins the walked set (an
AcqRelread-modify-write) before the new shape tag, so any consumer that sees the new shape also sees that the old one is still walked. - new
try_sends route to the new backing;try_recvdrains every other walked shape before the current one, so an item pushed microseconds before the flip is consumed before the new backing is read - nothing is lost, FIFO across the seam holds.
A shape that has been used is walked for the life of the ring. The set only grows, and that is what makes it correct: a producer resolves the shape tag and pushes some instructions later, so a backing can receive a push after it stops being current, and nothing can know that push is coming. There are four shapes, so never forgetting one costs a bounded walk rather than a race. No data is copied between backings; each keeps its single reader and a new one starts empty.
This is verified by the test suite, not asserted - among others,
morph_preserves_in_flight_items_via_stale_walk,
two_morphs_in_a_row_strand_nothing,
a_push_landing_two_morphs_late_is_still_delivered, and
stamped_items_survive_shape_morphs all exercise shape morphs under live
traffic. The composed MPMC path (SharedRingMpmc) is exercised at 4
producers x 2 consumers, 40,000 items (PER_PRODUCER = 10_000), zero lost
and zero duplicated.
Obtaining a primitive from several processes
For the coordination primitives - SharedRWLock, BlockingRWLock,
OwnerLease, HeartbeatTable, SharedCondvar, CrossProcessWaker,
SharedLeaderElection, SharedOnceCell, SharedCell, the
SharedAtomic* trio, SharedFenceClock, SharedHandleTable,
SharedRateLimiter, SharedTimePointTile, SharedHistogram,
SharedBitVec, SharedBloomFilter, SharedBlockedBloomFilter,
SharedCountMinSketch, SharedHyperLogLog,
SharedReservoirSampler, SharedBroadcastRing (file-backed),
SharedTreiberStack, SharedVec, SharedStringArena,
SharedTopologyMap, SharedBTreeMap, SharedRegion, FrameRing
(file-backed), SharedUniversal, SpscRingCore (file-backed, and
the file-backed constructors built on it), DirectFileRing,
PubSubRing (file-backed), SharedVersionedChain,
SharedHugepageRegion, FrameRegion (file-backed), the
AdaptiveRing peer directory - and for SharedHashMap - create
obtains the instance:
it initializes the file only when the path does not yet exist, and
otherwise attaches with live state intact. Racing creators on one path
all reach the same instance, with exactly one initializing it. Each of
these types carries a reset; most truncate and reinitialize, for a
caller that owns the path, and on Windows such a reset succeeds only
once every process has unmapped the region. SharedRateLimiter and
SharedHistogram instead carry an in-place reset() that reseeds
the live instance.
Every file-backed primitive outside the owner-exclusive set below now
obtains this way; none is left truncating on create. The anonymous
and named-shared-memory constructors (create_anon, create_from_shm)
are unchanged: they build a fresh region by definition, and
create_or_open_shm is the attaching peer of the shm pair.
The owner-exclusive primitives - the SharedDeque family,
SharedRing and the ordering types - keep truncate-on-create by
design: their create is called by the single owner their protocol
names (thieves and consumers use open_as_thief / open), so racing
creators are outside their contract and attach semantics would record
a stale owner.
What you must not do
- Do not put two producers on a single-producer ring. On the typed SPSC
pair this will not compile. On a raw
SpscRingCoreopened cross-process, nothing at compile time stops you - SPSC means exactly one producer and one consumer total, and cross-process that is a convention you uphold. If in doubt, use theAdaptiveRingorSharedRing(MPMC), which have no such limit. - Do not wrap a ring in a process-private lock (
Mutex/RwLock). It adds cost and does not work across the process boundary the in-MMF atomics handle. - Do not push or pop with a peer id you did not register. Slot ids come
from
register_producer/register_consumer(shared, recycled on unregister); inventing one risks two writers on a single-writer backing.
In one sentence
You just register, send / recv, and unregister: the ring claims a slot
for each peer, grows its backings when peers outnumber the construction hint,
holds no locks, picks its own shape, and stays thread- and process-safe even
as it morphs beneath your live producers and consumers.