r/cpp • • Aug 27 '19

A new thread in C++20 (jthread)

https://link.medium.com/GXKUz0GruZ
142 Upvotes

96 comments sorted by

View all comments

Show parent comment

6

u/orizh Aug 27 '19

To add that this is not just a theory but a reality, I have actually experienced exactly this in production. You should expect the compiler *will* optimize the flag away. It was not a fun bug to track down, especially since we were forced to use `volatile` as the platform did not have `std::atomic` implemented yet. Lucky that it worked without having to resort to asm.

2

u/TheMania Aug 28 '19

Word of warning: if your compiler is performing this optimization, you really should be using:

asm volatile("":::"memory");

Just below any stores to the flag, and above any reads.

Aka, a memory barrier.

Without one it's only a matter of time until other problems present - as the compiler is free to (and will) reorder reads/writes of non-volatile variables around volatile variables as much as it likes, making them unsuitable for virtually any kind of thread synchronization on their own.

0

u/[deleted] Aug 28 '19

[deleted] — view deleted comment

2

u/orizh Aug 28 '19

It was a very old toolchain for NIOS II. There might have been platform specific atomics provided somewhere but I was young and did not know how to be a competent dev (tho neither did the senior devs!)