Search code examples
c#multithreadingthread-sleep

How Thread.Sleep() works?


So i tried to study how to use multi-threading, and I have noticed something which I don't quite get.

In the next piece of code, it seems like doo() starts running before the Thread is finished, although foo is the same as the Thread:

static void Main(string[] args)
{
    new Thread(new ThreadStart(foo)).Start();
    foo();
    doo();
}

public static void foo()
{

    Console.WriteLine("1");
    Thread.Sleep(3000);
    Console.WriteLine("2");
}

public static void doo()
{
    Console.WriteLine("do");
}

The output is:

1 //Thread

1 //foo

2 //foo

do //doo

2 //Thread

Assuming that doo() can not start running without foo() is done, we assume that the last "2" output came from the first thread.

How is it possible? Although foo() and the Thread have the same sleeping time since they are the same functions, how come that the Thread (which is executed first) is the last one to finish?

Lock Statement

Now, if we add a lock statement, like this:

static object syncLock = new object();

static void Main(string[] args)
{
    new Thread(new ThreadStart(foo)).Start();
    foo();
    doo();
}

public static void foo()
{
    lock (syncLock)
    {
        Console.WriteLine("1");
        Thread.Sleep(3000);
        Console.WriteLine("2");
    }        
}

public static void doo()
{
    Console.WriteLine("do");
}

The output is:

1 //Thread

2 //Thread

1 //foo

do //doo

2 //Thread

Now it seems like doo() starts running before foo() ends! What is happening here? What is the process and the logic behind it?


Solution

  • Look, you have here actually two threads, on main and the second thread(foo()) .. After new Thread(new ThreadStart(foo)).Start(); executing will start with main thread, that mean this thread(main thread) will try to call foo(), that is your "1" , after that, main thread go to sleep and second thread star foo() , that is second-one "1" ,and sec go to sleep.. Now main thread will wake up and will finish the job "2", "do", and the last "2" is from sec thread. That is without a locking.

    With locking, main thread will do foo() and the sec will be blocked("1",3sec,"2"), when foo() is unlock that mean, sec thread can call foo(), and when that happens sec print "1" ad go to sleep, and now(while sec is sleeping CPU looking for thread that can be executed), so CPU exe a main thread and print a "do" and then sec will wake up and print "2"..