赛车条件示例

Racing condition examples

在硬件和软件方面有哪些赛车条件的实际例子? 示例不应该是关于解释什么是竞争条件的代码,而是系统中的一种情况。

例如 - 当两个音乐播放器试图访问扬声器时。

你在 https://support.microsoft.com/en-us/help/317723/description-of-race-conditions-and-deadlocks

上用一个简单的例子给出了很好的解释

我会引用最重要的部分(说实话几乎是完整的文章)。

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.

编辑:如果我在这里错了,请有人纠正我。

我看到您已经编辑了您的问题以明确您的疑问,因此我将相应地扩展我的回答。实际上,有两个音乐播放器试图访问扬声器以输出声音可能与有两个线程试图写入 stdout 没有什么不同。有一个公共缓冲区,数据被发送到该缓冲区,然后由驱动程序(在扬声器的情况下)进行处理。 stdout 示例的结果是字符可以交错,在扬声器中也会发生同样的情况:声音会交错,因为它不能同时播放。因此,竞争条件的后果也适用于 "system situation".