using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ThreadExample
{
public class Info
{
public int Counter;
private static object _lock = new object();
private List<Thread> ThreadList;
public Info(int counter)
{
Counter = counter;
ThreadList = new List<Thread>();
ThreadList.Add(new Thread(ThreadBody));
ThreadList.Add(new Thread(ThreadBody));
ThreadList[0].Name = "t1";
ThreadList[1].Name = "t2";
}
public void Start()
{
ThreadList.ForEach(t => t.Start(t.Name));
}
public void ThreadBody(object name)
{
while (Counter != 20)
{
lock (_lock)
{
Counter++;
Console.WriteLine("Thread {0} : the value of the counter is {1}", name.ToString(), Counter);
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ThreadExample
{
class Program
{
static void Main(string[] args)
{
Info info = new Info(0);
info.Start();
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果锁只是锁定计数器++ lock(_lock){Counter ++; 我没有无限循环,但如果锁在示例中,则运行无限循环
可能是当Counter到达19时,两个线程都进入循环并且在它们再次测试值之前最终增加到21.
你需要在读取值时按住锁定Counter.双重检查Counter可能就足够了(while在握住锁的同时在循环内重新读取它).但是,我不确定这一点,因为我的头脑无法跟踪本机,.NET,Java等各种线程内存模型的所有细节.即使在.NET上,ECMA模型显然也不同于MS对其CLR的保证(参见http://msdn.microsoft.com/en-us/magazine/cc163715.aspx和http://www.bluebytesoftware.com/blog /PermaLink,guid,543d89ad-8d57-4a51-b7c9-a821e3992bf6.aspx).有关为什么重复检查可能会或可能不起作用的详细信息,请搜索"双重检查锁定" - 显然应该很简单的事情背后有很多复杂性.
例如,这是我机器上运行的片段:
Thread t1 : the value of the counter is 1
Thread t2 : the value of the counter is 2
Thread t2 : the value of the counter is 3
Thread t2 : the value of the counter is 4
Thread t2 : the value of the counter is 5
Thread t2 : the value of the counter is 6
Thread t2 : the value of the counter is 7
Thread t2 : the value of the counter is 8
Thread t2 : the value of the counter is 9
Thread t2 : the value of the counter is 10
Thread t2 : the value of the counter is 11
Thread t2 : the value of the counter is 12
Thread t2 : the value of the counter is 13
Thread t2 : the value of the counter is 14
Thread t2 : the value of the counter is 15
Thread t2 : the value of the counter is 16
Thread t2 : the value of the counter is 17
Thread t2 : the value of the counter is 18
Thread t2 : the value of the counter is 19
Thread t2 : the value of the counter is 20
Thread t1 : the value of the counter is 21
Thread t1 : the value of the counter is 22
... Thread t1 never stops ...
Run Code Online (Sandbox Code Playgroud)
t2一旦Counter达到20,你会注意到停止,但是t1没有注意到.它已经进入循环(或决定进入循环),认为Counter是1(或者可能是2或其他东西 - 只是不是20).
| 归档时间: |
|
| 查看次数: |
1068 次 |
| 最近记录: |