C#线程和锁定

时间:2017-10-18 09:49:12

标签: c# multithreading locking

我测试简单代码

    static Thread _readThread = null;
    static private Object thisLock = new Object();
    static int a = 1;

    private static void ReadComPort()
    {
        lock (thisLock)
        {
            for (int i = 0; i < 3; i++)
            {
                Console.WriteLine(Thread.CurrentThread.Name + "  " + a++.ToString());
                Thread.Sleep(1000);
            }
        }
    }

    static void Main(string[] args)
    {
        for (int i = 0; i < 3; i++)
        {
            _readThread = new Thread(new ThreadStart(ReadComPort));
            _readThread.IsBackground = true;
            _readThread.Name = i.ToString();
            _readThread.Start();
            //Thread.Sleep(50);
        }

        Console.WriteLine("End");
        Console.ReadKey();
    }

但是为什么执行顺序和线程的启动是混乱的: 0,2,1为什么?

控制台输出:

0  1
End
0  2
0  3
2  4
2  5
2  6
1  7
1  8
1  9

3 个答案:

答案 0 :(得分:2)

因为您不能指望线程以特定顺序启动或运行。操作系统以其想要的方式安排线程。有时它会将一个线程置于保持状态,执行另一个线程,然后再返回原始线程。

在这里,您可以看到线程几乎同时启动。显然(从输出)线程0赢得它到第一个锁。然后,通过纯粹的机会,线程2比线程1早得到锁。由于线程是在彼此之后不久创建的,因此可能完全不同。如上所述:无法保证。

答案 1 :(得分:2)

Lock不保证订单:Does lock() guarantee acquired in order requested?

此外,在您的代码中,您应该等待线程在for循环结束时完成,以便在开头没有“结束” - 如果您按一个键,您将在线程仍在运行时退出,你可能会有意想不到的行为。

答案 2 :(得分:0)

仔细阅读C#参考。

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/lock-statement

在那里,你找不到任何关于进入锁定区块的线程顺序。

相关问题