-1

I test simple code

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

but why is the sequence of execution and the launching of threads chaotic: 0,2,1 Why?

Console output:

0  1
End
0  2
0  3
2  4
2  5
2  6
1  7
1  8
1  9
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
Serjaru
  • 89
  • 1
  • 9
  • 2
    What were you *expecting* and *why*? Note that your low iteration counts mean that any interactions *between* threads are unlikely. – Damien_The_Unbeliever Oct 18 '17 at 09:53
  • When a thread is started it is not guaranteed to run immediately nor in the order of being started compared to other threads – Emond Oct 18 '17 at 09:53
  • You can use `Task.ContinueWith`, queue to run threads, queue/priority to synchronize access to Console, what else.. should be more, but definitely not running some threads and expecting them to organize themselves as you didn't tell them to... – Sinatr Oct 18 '17 at 10:12
  • Well, you don't want more than 1 thread pulling your ComPort anyway. – H H Oct 18 '17 at 10:15

3 Answers3

2

Because you can't expect threads to start or run in a specific order. The OS schedules threads the way it wants to. Sometimes it puts a thread on hold, executes another one, before coming back to the original one.

Here you see that the threads start almost at the same time. Obviously (from the output) thread 0 wins it to the first lock. Then, by pure chance, thread 2 gets by the lock earlier than thread 1. This could have gone entirely different since the threads are created shortly after each other. As said: there is no guarantee.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
2

Lock does not guarantee the order : Does lock() guarantee acquired in order requested?

Also, in your code, you should wait your threads to finish at the end of your for loop in order to not have "end" at the beginning - if you press a key, you will exit while your thread are still running, and you may have unexpected behaviour.

Treziac
  • 3,056
  • 1
  • 17
  • 19
0

Read the C# reference carefully.

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

There, you cannot find anything about the order of threads entering the lock block.

BHP
  • 443
  • 4
  • 13