views:

75

answers:

1
Thread t = new Thread (WriteY);
t.Start();            
for (int i = 0; i < 1000; i++) Console.Write ("x");

static void WriteY()
{
    for (int i = 0; i < 1000; i++) Console.Write ("y");
} 

internally How does thread work ? means why output of above code is not fix every time i run, sequence of 'x' and 'y' is different?

+5  A: 

All multitasking systems have a scheduler. A scheduler decides what unit of work will execute next. A basic scheduler can be something that runs of a high resolution timer (like, say, every 100ms, a task switch happens). Clearly, modern implementations are much more complicated than that.

That said, most modern threading implementations rely on a scheduler within the kernel. Many of these schedulers are NOT deterministic. That is, there is no guarantee that a context switch (i.e. a switch between runnable instances managed by the scheduler) will happen at any specific time.

What you are seeing are the discrepancies in that scheduler for your system.

Will Hartung
Thanks for answer, Will i want to know about scheduler, is it a new concept in operating system if yes then how it communicate with os kernal.
Jeevan Bhatt
The scheduler is part of the kernel. It is what decides which thread or process to run on which CPU (if there is more than one) and how much time to give each thread or process before suspending it and switching to another one.
Anthony Williams
@Jeevan: Will is right; modern implementations are *way* more complicated than that. See http://en.wikipedia.org/wiki/Scheduling_(computing) for an overview of various scheduling techniques.
Eric Lippert