0

If I have two threads running the below piece of code without a lock, what would be the value or range of values of x in the end?

x = 0; 
for (int i=0; i<10;i++) x++;
  • 1
    Depends on the type of `x` and the number of threads. Try it for yourself and see, I would say. – Botje May 07 '20 at 07:48
  • 4
    Undefined Behaviour: _"If a data race occurs, the behavior of the program is undefined."_ source: https://en.cppreference.com/w/cpp/language/memory_model When you have UB no analysis is possible. – Richard Critten May 07 '20 at 07:51
  • @Botje Too bad, but for possible data races and other undefined behavior, "try it yourself" is not a good advice. Worst case, it would behave as expected, so there could be an impression that there is no problem. – stefaanv May 07 '20 at 08:00
  • @Botje There are two threads and x is of type int, What would be the minimum and maximum values given the worst case – Angadishop May 07 '20 at 08:03
  • FYI: [SO: While loop in main thread is getting stuck when using std::thread](https://stackoverflow.com/a/57177535/7478597) – Scheff's Cat May 07 '20 at 08:03
  • With `int x;` it's Undefined Behavior. It would work with `std::atomic x;`. – Scheff's Cat May 07 '20 at 08:04
  • @Scheff Can't we even predict the worst-case values? – Angadishop May 07 '20 at 08:07
  • If it's Undefined Behavior it's unpredictable by definition. With `std::atomic x(0);` and two threads with 10 iterations each it will be 20 (after joining both) and that's completely predictable. ;-) – Scheff's Cat May 07 '20 at 08:09
  • 2
    Please provide a [mcve]. What this code does depends on the type of `x`. It could be fine, it could be not. Given only the code you posted one cannot know – 463035818_is_not_a_number May 07 '20 at 08:21
  • If you think "Blablabla U.B. - I just see this running on my box and it ends up somewhere in the range [0, 20]" then this might be of interest: [SO: Multithreading program stuck in optimized mode but runs normally in -O0](https://stackoverflow.com/q/58516052/7478597) ;-) – Scheff's Cat May 07 '20 at 08:23

0 Answers0