0
int y = 0;  // global

void ThreadFunc(int &y){  // local reference var that shadows the global
  y += 2;
}

If this is being run from 5 threads, can y = 8? If so, what would this look like in assembly language that would lead y = 8?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Roger Fed
  • 1
  • 2
  • This sounds like a homework question; what are your thoughts? – Nate Eldredge Apr 12 '21 at 04:37
  • Actually, wouldnt multiple threads push and pop into a race condition making it unsafe? – Roger Fed Apr 12 '21 at 04:40
  • 1
    I mean, the whole thing is a big race condition (and thus undefined behavior at the level of the C++ language). I'm not sure what you mean by "push and pop"; each thread will have its own stack so there's no conflict there. – Nate Eldredge Apr 12 '21 at 04:48
  • In C++, yes, for plain `int y` (not `std::atomic`), it would be Undefined Behaviour for multiple unsynchronized threads to write `y`. See [Can num++ be atomic for 'int num'?](https://stackoverflow.com/q/39393850) for C++ vs. asm. Actually that has answers which explain the asm / cpu-architecture details of non-atomic increments stepping on each other. Also, are they all supposed to be called with their arg referring to the global `y`? Why bother having an arg at all? Seems like it would be a better example with ThreadFunc directly accessing the global. – Peter Cordes Apr 12 '21 at 04:48

0 Answers0