C++ : std::atomic and volatile bool

后端 未结 3 2103
一向
一向 2020-12-30 02:55

I\'m just reading the C++ concurrency in action book by Anthony Williams. There is this classic example with two threads, one produce data, the other one consumes the data a

3条回答
  •  误落风尘
    2020-12-30 03:10

    Ben Voigt's answer is completely correct, still a little theoretical, and as I've been asked by a colleague "what does this mean for me", I decided to try my luck with a little more practical answer.

    With your sample, the "simplest" optimization problem that could occur is the following:

    According to the Standard, an optimized execution order may not change the functionality of a program. Problem is, this is only true for single threaded programs, or single threads in multithreaded programs.

    So, for writer_thread and a (volatile) bool

    data.push_back(42);
    data_ready = true;
    

    and

    data_ready = true;
    data.push_back(42);
    

    are equivalent.

    The result is, that

    std::cout << "The answer=" << data[0] << "\n";
    

    can be executed without having pushed any value into data.

    An atomic bool does prevent this kind of optimization, as per definition it may not be reordered. There are flags for atomic operations which allow statements to be moved in front of the operation but not to the back, and vice versa, but those require a really advanced knowledge of your programming structure and the problems it can cause...

提交回复
热议问题