当内部有循环时,锁定语句不起作用?

时间:2009-03-19 13:18:26

标签: c# multithreading locking

请参阅此代码:

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

我做错了什么?

1 个答案:

答案 0 :(得分:21)

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

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