0

I'm really new to multi-thread programming. Really confused about the definition. Say I have two threads

x, y, z = 0;

Thread 1:
lock(x);
lock(y);
x = y + 1;
unlock(x);
unlock(y);

Thread 2:
lock(x);
lock(z);
z = x + 1;
unlock(x);
unlock(z);

You can see that the value of z is dependent on which thread execute first. If thread 1 happens before thread 2, z = 2; if thread 2 executes first, z = 1. According to many existing answers, e.g. Is this a race condition?, I believe many people think it's not. But the result is unpredictable - depend on thread scheduling still sounds weird to me. It this a semantic mistake? Do people ever write multi-thread programs like this? Thanks for any comments!!

  • You seem to understand the behaviour, and we all agree that there is a race. The code is fine if that is the acceptable/intended behaviour. If the behaviour is not what you want, then the code is wrong. – Matt Timmermans Feb 26 '20 at 18:31
  • You might get different answers depending on who you ask. I was taught to say "data race" if different outcomes were possible, and "race condition" if any of those possible outcomes was undesirable. In the C++ community "race condition" usually means you have _broken the rules_ of how to write multi-threaded programs, and you have invoked the dreaded, "Undefined Behavior" (a.k.a., "UB"). When you invoke UB, the C++ compiler and/or language support library are allowed to spank you. – Solomon Slow Feb 26 '20 at 19:07
  • P.S., I think the variable, `y`, is superfluous in your example. Your thread 1 could just `lock(x); x=1; unlock(x);` and the final value of `z` still would depend on the order in which the threads ran. – Solomon Slow Feb 26 '20 at 19:10

0 Answers0