gpt4 book ai didi

C#线程问题为什么这里无限循环?

转载 作者:太空宇宙 更新时间:2023-11-03 17:27:35 25 4
gpt4 key购买 nike

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();
}
}
}

如果锁只是锁计数器++ 锁(_锁) { 计数器++; } 我没有无限循环,但如果锁像示例中那样,它会运行无限循环

最佳答案

可能是当 Counter 达到 19 时,两个线程都进入了循环,并且在它们再次测试该值之前它最终增加到 21。

您需要在读取 Counter 的值时持有锁。双重检查 Counter 可能就足够了(在 while 循环中再次读取它,同时持有锁)。但是,我对此不确定,因为我的头脑无法跟踪 native 、.NET、Java 等之间的各种线程内存模型的所有细节。即使在 .NET 上,ECMA 模型也明显不同于 MS 对其 CLR 的保证(参见 http://msdn.microsoft.com/en-us/magazine/cc163715.aspxhttp://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 ...

您会注意到 t2Counter 达到 20 后停止,但 t1 没有注意到这一点。它已经进入循环(或决定进入循环)认为 Counter 是 1(或者可能是 2 或其他东西 - 只是不是 20)。

关于C#线程问题为什么这里无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6141082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com