71

I wrote a simple multithreading programs as follows:

static bool finished = false;

int func()
{
    size_t i = 0;
    while (!finished)
        ++i;
    return i;
}

int main()
{
    auto result=std::async(std::launch::async, func);
    std::this_thread::sleep_for(std::chrono::seconds(1));
    finished=true;
    std::cout<<"result ="<<result.get();
    std::cout<<"\nmain thread id="<<std::this_thread::get_id()<<std::endl;
}

It behaves normally in debug mode in Visual studio or -O0 in gcc and print out the result after 1 seconds. But it stuck and does not print anything in Release mode or -O1 -O2 -O3.

1
  • Comments are not for extended discussion; this conversation has been moved to chat.
    – Samuel Liew
    Oct 25, 2019 at 21:37

3 Answers 3

105

Two threads, accessing a non-atomic, non-guarded variable are U.B. This concerns finished. You could make finished of type std::atomic<bool> to fix this.

My fix:

#include <iostream>
#include <future>
#include <atomic>

static std::atomic<bool> finished = false;

int func()
{
    size_t i = 0;
    while (!finished)
        ++i;
    return i;
}

int main()
{
    auto result=std::async(std::launch::async, func);
    std::this_thread::sleep_for(std::chrono::seconds(1));
    finished=true;
    std::cout<<"result ="<<result.get();
    std::cout<<"\nmain thread id="<<std::this_thread::get_id()<<std::endl;
}

Output:

result =1023045342
main thread id=140147660588864

Live Demo on coliru


Somebody may think 'It's a bool – probably one bit. How can this be non-atomic?' (I did when I started with multi-threading myself.)

But note that lack-of-tearing is not the only thing that std::atomic gives you. It also makes concurrent read+write access from multiple threads well-defined, stopping the compiler from assuming that re-reading the variable will always see the same value.

Making a bool unguarded, non-atomic can cause additional issues:

  • The compiler might decide to optimize variable into a register or even CSE multiple accesses into one and hoist a load out of a loop.
  • The variable might be cached for a CPU core. (In real life, CPUs have coherent caches. This is not a real problem, but the C++ standard is loose enough to cover hypothetical C++ implementations on non-coherent shared memory where atomic<bool> with memory_order_relaxed store/load would work, but where volatile wouldn't. Using volatile for this would be UB, even though it works in practice on real C++ implementations.)

To prevent this to happen, the compiler must be told explicitly not to do.


I'm a little bit surprised about the evolving discussion concerning the potential relation of volatile to this issue. Thus, I'd like to spent my two cents:

26
  • 4
    I took one look at func() and thought "I could optimise that away" The optimiser doesn't care for threads at all, and will detect the infinite loop, and will happily turn it into a "while(True)" If we look at godbolt.org/z/Tl44iN we can see this. If finished is True it returns. If not, it goes into an unconditional jump back to itself (an infinite loop) at label .L5
    – Baldrickk
    Oct 23, 2019 at 16:21
  • 3
    @val No. SO: When to use volatile with multi threading? Oct 23, 2019 at 20:23
  • 2
    @val: there's basically no reason to abuse volatile in C++11 because you can get identical asm with atomic<T> and std::memory_order_relaxed. It does work though on real hardware: caches are coherent so a load instruction can't keep reading a stale value once a store on another core commits to cache there. (MESI) Oct 24, 2019 at 4:38
  • 5
    @PeterCordes Using volatile is still UB though. You really should never assume something that is definitely and clearly UB is safe just because you can't think of a way it could go wrong and it worked when you tried it. That has gotten people burned over and over. Oct 24, 2019 at 5:52
  • 3
    @Damon Mutexes have release/acquire semantics. The compiler is not allowed to optimize the read away if a mutex was locked before, so protecting finished with a std::mutex works (without volatile or atomic). In fact, you can replace all atomics with a "simple" value + mutex scheme; it would still work and just be slower. atomic<T> is allowed to use an internal mutex; only atomic_flag is guaranteed lock-free.
    – Erlkoenig
    Oct 25, 2019 at 11:17
45

Scheff's answer describes how to fix your code. I thought I would add a little information on what is actually happening in this case.

I compiled your code at godbolt using optimisation level 1 (-O1). Your function compiles like so:

func():
  cmp BYTE PTR finished[rip], 0
  jne .L4
.L5:
  jmp .L5
.L4:
  mov eax, 0
  ret

So, what is happening here? First, we have a comparison: cmp BYTE PTR finished[rip], 0 - this checks to see if finished is false or not.

If it is not false (aka true) we should exit the loop on the first run. This accomplished by jne .L4 which jumps when not equal to label .L4 where the value of i (0) is stored in a register for later use and the function returns.

If it is false however, we move to

.L5:
  jmp .L5

This is an unconditional jump, to label .L5 which just so happens to be the jump command itself.

In other words, the thread is put into an infinite busy loop.

So why has this happened?

As far as the optimiser is concerned, threads are outside of its purview. It assumes other threads aren't reading or writing variables simultaneously (because that would be data-race UB). You need to tell it that it cannot optimise accesses away. This is where Scheff's answer comes in. I won't bother to repeat him.

Because the optimiser is not told that the finished variable may potentially change during execution of the function, it sees that finished is not modified by the function itself and assumes that it is constant.

The optimised code provides the two code paths that will result from entering the function with a constant bool value; either it runs the loop infinitely, or the loop is never run.

at -O0 the compiler (as expected) does not optimise the loop body and comparison away:

func():
  push rbp
  mov rbp, rsp
  mov QWORD PTR [rbp-8], 0
.L148:
  movzx eax, BYTE PTR finished[rip]
  test al, al
  jne .L147
  add QWORD PTR [rbp-8], 1
  jmp .L148
.L147:
  mov rax, QWORD PTR [rbp-8]
  pop rbp
  ret

therefore the function, when unoptimised does work, the lack of atomicity here is typically not a problem, because the code and data-type is simple. Probably the worst we could run into here is a value of i that is off by one to what it should be.

A more complex system with data-structures is far more likely to result in corrupted data, or improper execution.

11
  • 6
    C++11 does make threads and a thread-aware memory model part of the language itself. This means compilers can't invent writes even to non-atomic variables in code that doesn't write those variables. e.g. if (cond) foo=1; can't be transformed to asm that's like foo = cond ? 1 : foo; because that load+store (not an atomic RMW) could step on a write from another thread. Compilers were already avoiding stuff like that because they wanted to be useful for writing multi-threaded programs, but C++11 made it official that compilers had to not break code where 2 threads write a[1] and a[2] Oct 24, 2019 at 4:27
  • 2
    But yes, other than that overstatement about how compilers aren't aware of threads at all, your answer is correct. Data-race UB is what allows hoisting loads of non-atomic variables including globals, and the other aggressive optimizations we want for single-threaded code. MCU programming - C++ O2 optimization breaks while loop on electronics.SE is my version of this explanation. Oct 24, 2019 at 4:31
  • 1
    @PeterCordes: One advantage of Java using a GC is that memory for objects won't be recycled without an intervening global memory barrier between the old and new usage, which means that any core that examines an object will always see some value that it has held at some time after the reference was first published. While global memory barriers can be very expensive if they're used frequently, they can greatly reduce the need for memory barriers elsewhere even when used sparingly.
    – supercat
    Oct 25, 2019 at 15:38
  • 1
    Yes, I knew that's what you were trying to say, but I don't think your wording 100% means that. Saying the optimizer "completely ignores them." isn't quite right: it's well known that truly ignoring threading when optimizing can involve things like word load / modify a byte in the word / word store, which in practice has caused bugs where one thread's access to a char or bitfield steps on a write to an adjacent struct member. See lwn.net/Articles/478657 for the full story, and how only the C11 / C++11 memory model makes such an optimization illegal, not just undesired in practice. Oct 25, 2019 at 20:50
  • 1
    No, that's good.. Thanks @PeterCordes. I appreciate the improvement.
    – Baldrickk
    Oct 26, 2019 at 5:04
5

For the sake of completeness in the learning curve; you should avoid using global variables. You did a good job though by making it static, so it will be local to the translation unit.

Here is an example:

class ST {
public:
    int func()
    {
        size_t i = 0;
        while (!finished)
            ++i;
        return i;
    }
    void setFinished(bool val)
    {
        finished = val;
    }
private:
    std::atomic<bool> finished = false;
};

int main()
{
    ST st;
    auto result=std::async(std::launch::async, &ST::func, std::ref(st));
    std::this_thread::sleep_for(std::chrono::seconds(1));
    st.setFinished(true);
    std::cout<<"result ="<<result.get();
    std::cout<<"\nmain thread id="<<std::this_thread::get_id()<<std::endl;
}

Live on wandbox

3
  • 1
    Could also declare finished as static within the function block. It will still be initialized only once, and if it’s initialized to a constant, this does not require locking.
    – Davislor
    Oct 23, 2019 at 22:00
  • The accesses to finished could also use cheaper std::memory_order_relaxed load and stores; there's no required ordering wrt. other variables in either thread. I'm not sure @Davislor's suggestion of static makes sense, though; if you had multiple spin-count threads you wouldn't necessary want to stop them all with the same flag. You do want to write the initialization of finished in a way that compiles to just initialization, not an atomic store, though. (Like you're doing with the finished = false; default initializer C++17 syntax. godbolt.org/z/EjoKgq). Jan 19, 2020 at 1:34
  • @PeterCordes Putting the flag in an object does allow there to be more than one, for different thread pools, as you say. The original design had a single flag for all threads, however.
    – Davislor
    Jan 19, 2020 at 20:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.