Planet PostgreSQL·· 8d ago
How PostgreSQL Orders Memory Accesses with Barriers, Volatile, and Atomics
Jan Kristof Nidzwetzki: Barriers, Volatile, and Atomics: How PostgreSQL Orders Memory Accesses
Brief · Based on the source excerpt
Jan Kristof Nidzwetzki explains PostgreSQL's memory and compiler barrier macros such as pg_memory_barrier(), pg_write_barrier(), pg_read_barrier(), and pg_compiler_barrier(), and why they are needed to stop compiler and CPU reordering from breaking shared-memory code.
Why It Matters
Shared-memory code that has long worked on x86 can fail on ARM, so its ordering assumptions need to be checked against the target platform’s memory model.
Technical Breakdown · Distilled from the original source
Ordering assumptions in shared memory
- PostgreSQL uses a process-based architecture, with a separate process handling each database connection. These processes communicate through shared memory and can read and write it concurrently. On a multiprocessor system, they can run on different CPU cores, each with its own cache.
- A writer can update two values in sequence without the reader necessarily observing the updates in that order. The article sets up this scenario with a
SharedStatestructure:tuplesstarts at0,donestarts atfalse, the writer runs on CPU 1, and the reader runs on CPU 2.
Reordering mechanisms and platform differences
- The article points to instruction scheduling, CPU pipelines, caches, store buffers, and invalidate queues when explaining reordering. It also considers the x86 and ARM memory models. Code that has worked for years on x86 can fail on ARM, including on platforms such as AWS Graviton servers and Apple Silicon machines.
- Barriers constrain reordering that could break correctness. The article discusses
pg_memory_barrier(),pg_write_barrier(),pg_read_barrier(), andpg_compiler_barrier()in the context of shared-memory access and also considers how locks, atomic operations, andvolatilefit in.
Source: Planet PostgreSQL· postgr.es
PG Radar summarizes verified changes and impact. Read the original post for full technical details and code samples.