A program’s behaviour depends on the order of execution. When using multithreading, the order in which threads are scheduled is decided by the processor. This may lead to two threads trying to access and change the same shared resource at the same time.
The condition of the program is hence dependant on the “relative timing or interleaving of multiple threads or processes”.1
A common problems is called the Check then act principle, where one thread may depend on a specific variable being set to a specific value. However, during checking and acting on this condition, another thread could have changed the value.
if (x == 5){ // Check
y = x * 2; // Act
}
// If another thread changed x in between "if (x == 5)" and "y = x * 2" above, y will not be equal to 10.
Since the next thread will have to wait until the lock is released, this could lead to an infinite loop and crash the process.
A nice real world example of this concept:
You are planning to go to a movie at 5 pm. You inquire about the availability of the tickets at 4 pm. The representative says that they are available. You relax and reach the ticket window 5 minutes before the show. I’m sure you can guess what happens: it’s a full house. The problem here was in the duration between the check and the action. You inquired at 4 and acted at 5. In the meantime, someone else grabbed the tickets. That’s a race condition - specifically a “check-then-act” scenario of race conditions.
Quelle:: multithreading - What is a race condition? - Stack Overflow
- Keywords:
- Quelle:
- Related: