为什么这些多线程代码在某些时候打印6?(Why does this multi

编程入门 行业动态 更新时间:2024-10-27 20:26:42
为什么这些多线程代码在某些时候打印6?(Why does this multi-threaded code print 6 some of the time?)

我创建了两个线程,并向它们传递了一个执行下面的代码显示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;

更多推荐

本文发布于:2023-08-04 11:25:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1415077.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多线程   代码   在某些   multi

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!