0

I'm a newbie to multi-threading in C#. I have created the following program:

class Program
{
    static void Main(string[] args)
    {
        Thread.CurrentThread.Name = "main";
        Thread t = new Thread(PrintName);
        t.Name = "worker";
        
        t.Start();
        PrintName();

        Console.ReadKey();
    }

    static void PrintName()
    {
        Console.WriteLine("Hello from " + Thread.CurrentThread.Name);
    }
}

The output is

Hello from main

Hello from worker

If I change the body of PrintName() method to

static void PrintName()
{
    if (Thread.CurrentThread.Name == "main")
    {
        Thread.Sleep(x);
    }

    Console.WriteLine("Hello from " + Thread.CurrentThread.Name);
}

where x >= 2, then the messages are output in reverse order

Why is that so? My reasoning is that in the first case, even though t.Start() precedes PrintName() in the Main() method, not enough time passes by for the thread scheduler to switch execution between main and worker threads, and hence the output. Can someone clarify/negate my assumptions?

Community
  • 1
  • 1
Kapol
  • 6,383
  • 3
  • 21
  • 46
  • 6
    You cannot expect any order at all, it is not guaranteed. If you need order in execution, you need to do it in a thread safe manner – kurast Aug 15 '14 at 20:15
  • 7
    The order of the output is non-deterministic, depending on your architecture, os etc. Starting a thread is relative expensive therefore in most cases the `main` message is printed first. – Andreas Aug 15 '14 at 20:15

1 Answers1

4

The question you're asking is typically the very first slide that's shown to university students in operating systems/introductory to multithreading courses. Essentially what you have is an execution of threads without the use of locks or other concurrency control techniques to specify your execution. As a result, your thread of execution is a sequence of instructions that are executed concurrently with other such sequences in the multithreading environment. When this occurs, as @Andreas and @kurast have mentioned, your program becomes stochastic. Essentially what this boils down to in C# is what byte code is executed first, which can change on every execution of the program. To solve this read up on concurrency control, race conditions, and critical sections in order to precisely define your thread's scheduling.

Here are a couple of good references for Multithreading:

  1. Mutex example / tutorial
  2. To Mutex or Not To Mutex?
  3. Parallel Processing and Concurrency in the .NET Framework

Please let me know if you have any questions!

Community
  • 1
  • 1
Devarsh Desai
  • 5,984
  • 3
  • 19
  • 21