0
        Thread thread1 = new Thread(new ThreadStart(c1.print));
        Thread thread2 = new Thread(new ThreadStart(c2.print));
        Thread thread3 = new Thread(new ThreadStart(c3.print));       

        thread1.Start();
        thread2.Start();
        thread3.Start();

When I run above code, sometimes thread 3 is printed before thread 1 and thread 2 even I specified thread1 to start 1st. Why does this happen?

Lyrk
  • 1,936
  • 4
  • 26
  • 48
  • 8
    Making any sort of assumptions about the relative execution order of threads will lead you into trouble. They might be running on separate cpu/cores. Don't assume. If you need stuff to happen in a specific order, use synchronization primitives to ensure that this happens. – spender Jun 14 '16 at 13:00
  • 1
    In a very brief nutshell: that's how multithreading works. The scheduler decides when each of the available threads gets a chance to run. – o_weisman Jun 14 '16 at 13:01
  • Just because you specified it to start first, doesn't mean it was given access to the CPU for processing time first. – Draken Jun 14 '16 at 13:03

2 Answers2

2

Just because you've called Start it doesn't mean the OS is obliged to start the thread at that point. It will schedule it for execution, and eventually it will get a timeslice to allow it to run, but it's pretty much non-deterministic when this will be.

In addition the OS may start the thread and then decide to suspend it whilst it scheduled some other threads. The key point here is that if you've got an ordering requirement between threads it's down to you to write code to make that ordering happen, not the OS schedulers.

Sean
  • 60,939
  • 11
  • 97
  • 136
0

Take a look at the example in this post.
The point of it is that you can use multiple threads to distribute work, but you should never have an expectation about the sequence in which they will run.
The threads may or may not start in the expected order. If they start in the expected order, they may not entirely execute or finish in the expected order.

The insidious "problem" is that more often than not they will execute in the expected sequence, leading the programmer to think that it's doing what they want. But then once in a while they won't run in that sequence. It will be difficult or impossible to reproduce or debug.

Community
  • 1
  • 1
Scott Hannen
  • 27,588
  • 3
  • 45
  • 62