c++, std::atomic, what is std::memory_order and how to use them?

The std::memory_order values allow you to specify fine-grained constraints on the memory ordering provided by your atomic operations. If you are modifying and accessing atomic variables from multiple threads, then passing the std::memory_order values to your operations allow you to relax the constraints on the compiler and processor about the order in which the operations … Read more

AtomicInteger lazySet vs. set

Cited straight from “JDK-6275329: Add lazySet methods to atomic classes”: As probably the last little JSR166 follow-up for Mustang, we added a “lazySet” method to the Atomic classes (AtomicInteger, AtomicReference, etc). This is a niche method that is sometimes useful when fine-tuning code using non-blocking data structures. The semantics are that the write is guaranteed … Read more

What are the various ways to disable and re-enable interrupts in STM32 microcontrollers in order to implement atomic access guards?

Multiple ways to enable/disable interrupts in STM32 mcus: 1. Via ARM-core CMSIS: 1.A. For global interrupts __enable_irq() // enable all interrupts __disable_irq() // disable all interrupts // Returns the current state of the priority mask bit from the Priority Mask // Register. [0 if global interrupts are **enabled** and non-zero if they // are **disabled**] … Read more

How to do an atomic increment and fetch in C?

GCC __atomic_* built-ins As of GCC 4.8, __sync built-ins have been deprecated in favor of the __atomic built-ins: https://gcc.gnu.org/onlinedocs/gcc-4.8.2/gcc/_005f_005fatomic-Builtins.html They implement the C++ memory model, and std::atomic uses them internally. The following POSIX threads example fails consistently with ++ on x86-64, and always works with _atomic_fetch_add. main.c #include <assert.h> #include <pthread.h> #include <stdlib.h> enum CONSTANTS … Read more

Which types on a 64-bit computer are naturally atomic in gnu C and gnu C++? — meaning they have atomic reads, and atomic writes

The answer from the point of view of the language standard is very simple: none of them are “definitively automatically” atomic. First of all, it’s important to distinguish between two senses of “atomic”. One is atomic with respect to signals. This ensures, for instance, that when you do x = 5 on a sig_atomic_t, then … Read more