我创建了两个线程,并向它们传递了一个执行下面的代码显示10,000,000次的函数。
大多数情况下,“5”被打印到控制台。 有时候是“3”或“4”。 这很清楚为什么会发生。
但是,它也打印“6”。 这怎么可能?
class Program { private static int _state = 3; static void Main(string[] args) { Thread firstThread = new Thread(Tr); Thread secondThread = new Thread(Tr); firstThread.Start(); secondThread.Start(); firstThread.Join(); secondThread.Join(); Console.ReadLine(); } private static void Tr() { for (int i = 0; i < 10000000; i++) { if (_state == 3) { _state++; if (_state != 4) { Console.Write(_state); } _state = 3; } } } }这是输出:
I'm creating two threads, and passing them a function which executes the code show below, 10,000,000 times.
Mostly, "5" is printed to the console. Sometimes it's "3" or "4". It's pretty clear why this is happening.
However, it's also printing "6". How is this possible?
class Program { private static int _state = 3; static void Main(string[] args) { Thread firstThread = new Thread(Tr); Thread secondThread = new Thread(Tr); firstThread.Start(); secondThread.Start(); firstThread.Join(); secondThread.Join(); Console.ReadLine(); } private static void Tr() { for (int i = 0; i < 10000000; i++) { if (_state == 3) { _state++; if (_state != 4) { Console.Write(_state); } _state = 3; } } } }Here is the output:
最满意答案
我想我已经弄清楚了导致这个问题的一系列事件:
线程1进入if (_state == 3)
上下文切换
线程2进入if (_state == 3) 线程2增加状态( state = 4 )
上下文切换
线程1 将 _state 读为4
上下文切换
线程2设置_state = 3 线程2进入if (_state == 3)
上下文切换
线程1执行_state = 4 + 1
上下文切换
线程2将_state读为5 线程2执行_state = 5 + 1 ;
I think I have figured out the sequence of events leading to this issue:
Thread 1 enters if (_state == 3)
Context switch
Thread 2 enters if (_state == 3) Thread 2 increments state (state = 4)
Context switch
Thread 1 reads _state as 4
Context switch
Thread 2 sets _state = 3 Thread 2 enters if (_state == 3)
Context switch
Thread 1 executes _state = 4 + 1
Context switch
Thread 2 reads _state as 5 Thread 2 executes _state = 5 + 1;
更多推荐
发布评论