bool 不是线程安全

 1          static bool isStop = false;
 2         static void Main()
 3         {
 4             var t = new Thread(() =>
 5             {
 6                 var isSuccess = false;
 7 
 8                 while (!isStop)
 9                 {
10                     isSuccess = !isSuccess;
11                 }
12             });
13 
14             t.Start();
15 
16             Thread.Sleep(1000);
17             isStop = true;
18             t.Join();
19 
20             Console.WriteLine("主线程执行结束!");
21             Console.ReadLine();
22         }

在debug版本没问题,在release版本下不能执行到打印“主线程执行结束!"这一步。 

改变

static bool isStop = false;=》
static voliate bool isStop = false;则没有问题

posted on 2021-06-16 14:20  Shine-Zhong  阅读(387)  评论(0编辑  收藏  举报

导航