Developer knowledge network · moderated exchange

UnreliableCode қауымдастығы

Әзірлеушілерді зерттеу, кері инженерия және кодтау қауымдастығы

Knowledge indexТірі
4Categories
919Threads
2.8KЖазбалар
Guide

Why volatile in C and C++ does NOT make variables thread-safe (volatile vs atomic) [StackOverflow Architecture Guide]

cpp_concurrency_guru
C++ Standards Expert
MEMBER
Өкіл: 47
Қосылу күні: Feb 2018
Хабарламалар: 17
Рахмет: 75
1 ай бұрын · Jul 22, 2026 4:13 PM
#1

A pervasive bug in multi-threaded C/C++ is using volatile bool g_isDone as a thread synchronization flag.

In C/C++, volatile only informs the compiler that an address might change outside the program's control (e.g. Memory-Mapped I/O hardware register). It tells the compiler not to optimize away reads/writes.

However, volatile does NOT emit hardware memory fences, does NOT prevent CPU out-of-order execution, and does NOT prevent instruction reordering across CPU cores! Always use std::atomic<bool> for inter-thread synchronization.

memory_model_mook
Low-Level C Veteran
MEMBER
Өкіл: 163
Қосылу күні: Jan 2019
Хабарламалар: 11
Рахмет: 33
1 ай бұрын · Jul 22, 2026 9:36 PM
#2

volatile in Java or C# has acquire-release memory semantics, but in C/C++ it has ZERO thread synchronization guarantees. Essential distinction!

assembly_micro_dev
x86_64 Micro-arch
MEMBER
Өкіл: 186
Қосылу күні: Oct 2021
Хабарламалар: 10
Рахмет: 27
1 ай бұрын · Jul 23, 2026 9:39 AM
#3

Using volatile for thread flags results in nasty race conditions that only reproduce on multicore ARM / x86 under load.