在看有关volatile的说明的时候,老是看有人拿下面这个例子来说明,对没有volatile修饰的变量来说,新线和可能只会读取寄存器或者cache的值我看了太多的介绍volatile的文章,都会举以下代码的例子,说在vs选择发布模式时,Worker方法中的while循环不会退出,以此来说明volatile的必要性但实际,我做了很多次试验,VS是选择发布模式,然后运行EXE,但是并不是像所说的,while循环在过了2秒后还是会退出
我不知道有些人在发博文的时候到底有没有自己亲自测试过这个问题
有什么办法可以印证这个问题吗?,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ThreadDemo2
{
class Program
{
private static bool flag;
static void Main(string[] args)
{
Thread th = new Thread(Worker);
th.Start();
Thread.Sleep(2000);
flag = true;
Console.WriteLine("flag became true!");
Console.Read();
}
static void Worker()
{
while (!flag)
{
}
Console.WriteLine("Done");
}
}
}
我不知道有些人在发博文的时候到底有没有自己亲自测试过这个问题
有什么办法可以印证这个问题吗?,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ThreadDemo2
{
class Program
{
private static bool flag;
static void Main(string[] args)
{
Thread th = new Thread(Worker);
th.Start();
Thread.Sleep(2000);
flag = true;
Console.WriteLine("flag became true!");
Console.Read();
}
static void Worker()
{
while (!flag)
{
}
Console.WriteLine("Done");
}
}
}
http://msdn.microsoft.com/zh-cn/library/x13ttww7.aspx
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.IO;
using System.Threading;namespace TJJTEST
{
class Program
{ static void Main(string[] args)
{
test t = new test();
t.Main();
// t = null;
Console.ReadKey();
}
} public class test
{
private bool flag = false;
public void Main()
{
Thread th = new Thread(Worker);
th.Start();
Thread.Sleep(2000);
flag = true;
Console.WriteLine("flag became true!");
//Console.ReadKey();
} void Worker()
{
flag = false;
while (!flag)
{
}
Console.WriteLine("Done");
}
}
{
flag = false;
while (!flag)
{
}
flag = true;
Console.WriteLine("Done");
}