What are some of the practical examples of racing condition in hardware and software? Example should not be about a code explaining what a race condition is but a situation in a system.
For example - When two music players are trying to access the speaker.
You have a very good explanation with a simple example at https://support.microsoft.com/en-us/help/317723/description-of-race-conditions-and-deadlocks
I will quote the most important part (which to be honest is almost the complete article).
Visual Basic code:
'Thread 1 Total = Total + val1 'Thread 2 Total = Total - val2
Assembly code (with line numbers) from the compilation of the preceding Visual Basic code:
'Thread 1 1. mov eax,dword ptr ds:[031B49DCh] 2. add eax,edi 3. jno 00000033 4. xor ecx,ecx 5. call 7611097F 6. mov dword ptr ds:[031B49DCh],eax 'Thread 2 1. mov eax,dword ptr ds:[031B49DCh] 2. sub eax,edi 3. jno 00000033 4. xor ecx,ecx 5. call 76110BE7 6. mov dword ptr ds:[031B49DCh],eax
By looking at the assembly code, you can see how many operations the processor is performing at the lower level to execute a simple addition calculation. A thread may be able to execute all or part of its assembly code during its time on the processor. Now look at how a race condition occurs from this code.
Total is 100, val1 is 50, and val2 is 15. Thread 1 gets an opportunity to execute but only completes steps 1 through 3. This means that Thread 1 read the variable and completed the addition. Thread 1 is now just waiting to write out its new value of 150. After Thread 1 is stopped, Thread 2 gets to execute completely. This means that it has written the value that it calculated (85) out to the variable Total. Finally, Thread 1 regains control and finishes execution. It writes out its value (150). Therefore, when Thread 1 is finished, the value of Total is now 150 instead of 85.
EDIT: Please someone correct me if I'm wrong here.
I've seen you've edited your question to specify your doubt so I'll extend my answer accordingly. In reality having two music players trying to access the speaker to output sound is probably not that different as having two threads trying to write to stdout
. There is a common buffer to which data is sent which is then processed by (in the case of the speaker) the driver. The consequences of the stdout
example is that the characters can be interleaved and in the speaker the same would occur: the sounds would be interleaved, since it can't play both simultaneously. Therefore the race condition consequences also apply to a "system situation".