Multithreading – is this a race condition?
Definition of competitive condition: racial condition or racial hazard is a defect in the system or process, in which the output or result of the process is unexpected and critical depending on the sequence or time of other events
Consider the following pseudocode:
Global variable i initialized to 6; Thread 1: acquire(lock l) increment global variable i,i.e. i++; Thread 2: acquire(lock l) double the value of global var i,i.e.: i*=2;
If T1 obtains lock l first and T2 seconds, the value of I will be 14 On the other hand, if T2 acquires lock l first and T1 acquires the ith value, the value of I will be 13
So is this a competitive condition?
Update: after many comments and answers, opinions are still different My opinion is in the "yes, this is racial condition" category In fact, I take this example as a case of racial conditions on another issue At the same time, I also read some interesting comments in the "no, not competition conditions" category I think I will determine and conclude whether this is a competitive condition or not according to the angle / level of observing this problem However, I am still waiting for interesting answers / comments
Solution
I think whether the example algorithm has competitive conditions depends on what the algorithm is expected to do
There is no data race for the modification of I - these accesses are serialized and occur atomically relative to each other
However, if the correctness of the algorithm is important to the correctness of the increment before multiplication (or vice versa), there is competition, and other means must be used to synchronize the execution of the algorithm If the algorithm is a complex method to calculate I * 21 (it may be ridiculous to use threads to perform calculations), there is a race condition
Consider the following program code snippets:
int data; pthread_cond_t condvar = PTHREAD_COND_INITIALIZER; pthread_mutex_t mux = PTHREAD_MUTEX_INITIALIZER; void* wait_for_data(void*) { pthread_mutex_lock( &mux); pthread_cond_wait( &condvar,&mux); puts("got the data: %d\n",data); pthread_mutex_unlock( &mux); return 0; } void* set_data(void*) { pthread_mutex_lock( &mux); data = 42; pthread_cond_signal( &condvar); pthread_mutex_unlock( &mux); return 0; }
The two threads are completely mutually exclusive in nature - there is no data contention However, if set_ Data() is waiting_ for_ Send condition variable before data() wait, wait_ for_ Data() will never complete I think most people will be called competitive conditions because they use conditional variables