Bloomberg LP Interview Question
Software Engineer / DevelopersSay, when in a system when one thread is partway from updating the data and the other thread access the same data, chaos is likely to occur and the result produced is not what expected and such kinds of bugs are called race condition where the threads racing one another to change the same data. To eliminate race conditions you need a way to make the operations atomic may be by employing some synchronization mechanism.
The key feature of a race condition is that it is not reproducible. Just like a car race if you run it N - times you will always get a differences (note you may get the same winner, just with a different time).
In the case of processes, it depends on how many are running, what they are doing, etc..
So another hallmark of race conditions is that they are notoriously hard to track down.
Race condition occurs when two or more threads performs an operation and result of an operation depends on unpredictable timing factor. For Eg:
If two threads executes an routine and each increment a same variable such as x=x+1 the variable could incremented twice and one of the thread could use wrong value like below:
1) Thread A increments var x;
2) Thread A is interrupted ( or blocked, or scheduled off), and thread B is started.
3) Thread B starts and increments variable x;
4). Thread B is interrupted (or blocked, or scheduled off), and thread A is started.
5). Thread A check the value of x and performs action based on values of x. The value of x differs from when thread A incremented it, and program behaviur is incorrect.
when a piece of code is shared between 2 threads
- morpheus February 12, 2009and when output of the code is different depending on the order in which that 2 threads execute that code...is race condition.
instead of code we can have any resources being shared here, instead of thread we can have processes.