Portable Compare And Swap atomic operations C/C library?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Portable compare-and-swap (CAS) should rely on language-standard atomics first, then provide compiler-specific fallbacks only where necessary. In modern C and C++, stdatomic.h and std::atomic already map to efficient platform instructions while preserving the memory-order guarantees your algorithm needs.
Many low-level Q and A style snippets solve the immediate error but skip the engineering context that keeps code reliable over time. A durable solution combines correct syntax with predictable behavior under real inputs, explicit failure handling, and verification that future refactors do not regress the outcome.
When evaluating a fix, also consider maintenance reality: who will own this code in six months, what observability exists in production, and which assumptions are most likely to break first. Capturing intent with small regression tests and clear naming drastically reduces re-learning cost when incidents happen under time pressure.
Core Sections
1. Start with the smallest correct implementation
In C11, wrap CAS in a small helper with explicit memory order choices. This keeps lock-free code readable and prevents accidental reliance on default sequential consistency when weaker ordering is sufficient.
This baseline should be intentionally simple. Keep naming precise, make assumptions visible, and avoid premature abstractions. Once the smallest version behaves correctly, you gain a trustworthy reference point for future optimization and architectural changes.
At this stage, add lightweight assertions or logging around critical state transitions. That evidence is invaluable when later optimizations accidentally change behavior, because you can quickly compare current output against the known-good baseline rather than guessing where divergence started.
2. Harden the implementation for real usage
In C++, compare_exchange_weak in a loop is common for update retries. Keep the expected value updated on each failure and ensure loop bodies are small to avoid contention amplification.
Production hardening is where many bugs are prevented. Address resource management, thread or event-loop safety, edge cases, and consistent error paths. If this logic is part of a service boundary, include clear contracts for inputs, outputs, and failure semantics.
It also helps to separate pure transformation logic from side-effectful operations such as network calls, database writes, or UI mutation. That split makes unit tests faster and deterministic, while integration tests can focus on boundary behavior and failure recovery policies.
3. Verify behavior and performance
Portability is mostly a build and API design problem. Expose one stable wrapper interface and hide platform conditionals internally. Then test on multiple architectures, including ARM and x86, because memory-order bugs may pass on one platform and fail on another due to different hardware behavior.
A practical verification loop is straightforward and effective: one happy-path test, one edge-case test, and one failure-path test. Then run with representative data volume or user interactions. If behavior changes after refactoring, keep the regression test so the same issue does not return later.
Performance validation should align with user impact. For APIs, inspect latency percentiles and error rate. For mobile features, monitor frame drops and main-thread stalls. For algorithms and libraries, track complexity growth and memory churn under scaled inputs. Metrics tied to real outcomes keep optimization decisions grounded.
Common Pitfalls
- Using non-atomic reads or writes around CAS and breaking correctness.
- Picking memory orders by habit instead of algorithm requirements.
- Assuming
weakandstrongbehave the same under all contention patterns. - Forgetting ABA risks in pointer-based lock-free structures.
- Shipping without stress tests that run under high thread contention.
Summary
Prefer standard atomics for portability and correctness. Keep CAS wrappers small, memory-order choices explicit, and concurrency tests aggressive across architectures. Pair concise implementation with explicit validation, and you get code that is both understandable today and maintainable as requirements evolve.
Related reading
- PostgreSQL asymmetric replication
- PostgreSQL Slony replication - scheduled sync
- Practical uses for AtomicInteger
- PRECONDITION_FAILED Delivery Acknowledge Timeout on Celery & RabbitMQ with Gevent and concurrency
- Possible to call C code from C?
- Problem with Precision floating point operation in C
- Preemptive threads Vs Non Preemptive threads
- Preventing task from running on certain thread
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.