简体   繁体   English

当里面有一个循环时,lock 语句不起作用?

[英]lock statement not working when there is a loop inside it?

See this code:请参阅此代码:

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

}

And this is the test run code:这是测试运行代码:

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

I would expect that m2 must execute from start to finish before m1 starts executing, or vice versa, because of the lock statement.由于lock语句,我希望m2必须在m1开始执行之前从头到尾执行,反之亦然。 But the result I found was the call to lock first and lock second was intermingled together, ie, something like this但是我发现的结果是lock first和lock second的调用混合在一起,即像这样

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

What did I do wrong?我做错了什么?

Each instance of the code is locking on a different object.代码的每个实例都锁定在不同的 object 上。 Your lock object needs to be shared between all instances -- make it a static class variable.您的锁 object 需要在所有实例之间共享 - 使其成为 static class 变量。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM