gpt4 book ai didi

c# - 当内部有循环时,lock 语句不起作用?

转载 作者:行者123 更新时间:2023-11-30 13:10:14 24 4
gpt4 key购买 nike

查看这段代码:

public class multiply
{
public Thread myThread;
public int Counter
{
get;
private set;
}
public string name
{
get;
private set;
}

public void RunConsolePrint()
{

lock(this)
{
RunLockCode("lock");
}


}

private void RunLockCode(string lockCode)
{
Console.WriteLine("Now thread "+lockCode+" " + name + " has started");
for (int i = 1; i <= Counter; i++)
{
Console.WriteLine(lockCode+" "+name + ": count has reached " + i + ": total count is " + Counter);
}
Console.WriteLine("Thread " + lockCode + " " + name + " has finished");
}
public multiply(string pname, int pCounter)
{
name = pname;
Counter = pCounter;
myThread = new Thread(new ThreadStart(RunConsolePrint));
}

}

这是测试运行代码:

    static void Main(string[] args)
{
int counter = 50;

multiply m2 = new multiply("Second", counter);
multiply m1 = new multiply("First", counter);
m1.myThread.Start();
m2.myThread.Start();
Console.ReadLine();
}

我希望 m2 必须在 m1 开始执行之前从头到尾执行,反之亦然,因为 lock 语句。但我发现的结果是先锁定和先锁定的调用混合在一起,即像这样

Now thread lock First has started
Now thread lock Second has started
lock First: Count has reached 1: total count is 50
lock First: Count has reached 2: total count is 50
lock Second: Count has reached 1: total count is 50

我做错了什么?

最佳答案

代码的每个实例都锁定在不同的对象上。您的锁对象需要在所有实例之间共享——使其成为静态类变量。

private static object syncRoot = new object();
public void RunConsolePrint()
{
lock(syncRoot)
{
RunLockCode("lock");
}
}

关于c# - 当内部有循环时,lock 语句不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/662156/

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