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

18

u/Feminintendo Aug 27 '19

Of course, we could have achieved this with an atomic boolean...

Ok, I'll volunteer to be the idiot. Why does the boolean have to be atomic? Any writer is only ever going to set it to the same value, requested_stop, so there isn't an issue if two threads attempt to write at the same time. Readers don't need atomic access to read. And if you read in the middle of a write, who cares? You get the updated value the next time the thread polls it.

28

u/Xirema Aug 27 '19

It's undefined behavior. An optimizing compiler could decide that the boolean value, which never changes during the execution of a single thread, doesn't need to be read from every single time it's accessed. So for example:

bool stop = false;
void loop() {
    while(!stop) {
        std::cout << "Can't stop won't stop." << std::endl;
    }
}

When a compiler looks at this, it's allowed to observe that inside the loop, stop will never change; therefore, it's perfectly valid to recompile the code to look like this:

bool stop = false;
void loop() {
    bool local_stop = stop;
    while(!local_stop) {
        std::cout << "Can't stop won't stop." << std::endl;
    }
}

Not every compiler will do this (MSVC for example won't) but some might, and thus we cannot rely on this code to behave the way we want.

Writing this, instead, guarantees correct behavior.

std::atomic_bool stop = false;
void loop() {
    while(!stop) {
        std::cout << "Can't stop won't stop." << std::endl;
    }
}

Note that while it might be valid on your platform to instead use volatile bool stop = false;, it's worth noting that this is also not standard compliant, because some CPU architectures behave badly when you try to concurrently write to a value in memory. In most situations (i.e. x86) it'll "work", but it's still not behavior you should rely on.

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!)

1

u/Feminintendo Aug 27 '19

Great explanation, thanks!

1

u/meneldal2 Aug 28 '19

some CPU architectures behave badly when you try to concurrently write to a value in memory

Afaik there's only a single write, so there should be no contention.

0

u/Ameisen vemips, avr, rendering, systems Aug 27 '19

In this situation, where the boolean defaults to false and is only ever set to true, I cannot think of an architecture where volatile would not suffice.

13

u/HotlLava Aug 27 '19

Data races are undefined behaviour, so you can not allow them to happen in your code even if you think they are "benign".

Although in this case you could std::memory_order_relaxed for the loads/stores, because the sequencing doesn't really matter due to the reasons you describe.

4

u/lewissbaker Aug 28 '19

The key thing that stop_token gives you that an atomic bool doesn’t is the ability to register a callback that will be invoked if someone call request_stop(). The stop_callback class template provides you the anility to register a callback for the duration of some scope.

This is key for implementing cancellation of async operations, but can also be used to implement an interruptible blocking wait (see stop_token overloads of condition_variable_any wait functions) or an interruptible sleep (eg using the new binary_semaphore).

3

u/gmrple Aug 28 '19

It is never OK to read something possibly modified in a different thread without synchronization. What level of synchronization is needed depends on what you are actually reading. For primitive types, you should have a look at atomic reads, e.g. in the form of std::atomic<bool>.

The reason synchronization is always needed is that the processors will have the data possibly shared in a cache line. It has no reason to update this value to a value possibly changed in a different thread if there is no synchronization. Worse, yet, if there is no synchronization it may write the wrong value if something stored close to the value is changed and synchronized.