Race Condition

2024.04.20 · 1 minute read

In the meeting, my colleague presented an overview of the spike in question, outlining the necessary steps for handling user consent.

It is the case that different system platforms send requests to calculate user privacy patterns to our service at the same time. The different platforms may be customers or third parties.

However, due to the asynchronous communication involved, a race condition would occur when the new requests are received.

What is Race condition ?

race condition or race hazard is the condition of an electronics, software, or other system where the system’s substantive behavior is dependent on the sequence or timing of other uncontrollable events, leading to unexpected or inconsistent results. It becomes a bug when one or more of the possible behaviors is undesirable.

Source: Race condition - Wikipedia

Understanding from Code perspective

A race condition arises when two or more threads attempt to modify shared data simultaneously. Given that the thread scheduling algorithm can switch between threads at any point, it is impossible to predict the order in which threads will access shared data. Consequently, the outcome of the data modification is contingent upon the thread scheduling algorithm, whereby both threads are essentially engaged in a race to access or alter the data.

if (x == 5) // The "Check"
{
 y = x * 2; // The "Act"
 // If another thread changed x in between "if (x == 5)" and "y = x * 2" above,
 // y will not be equal to 10.
}

In order to prevent race conditions from occurring, you would typically put a lock around the shared data to ensure only one thread can access the data at a time. This would mean something like this:

lockX(); // Obtain lock for x
if (x == 5)
{
   y = x * 2; // Now, nothing can change x until the lock is released.
   // Therefore y = 10
}
unlockX(); // release lock for x

Source: multithreading - What is a race condition? - Stack Overflow

Thank you for reading! Your support is appreciated.

If you enjoyed this, consider buying me a coffee. ☕️