Wednesday, December 3, 2008

A Threading Query

Consider the following block of code…
 
//Csharp code snippet..
Line 1: Thread t = new Thread (Go);    // Assume Go is some static method
Line 2: t.Start();
Line 3: t.Join();                      // Wait (block) calling thread until thread t ends 
//End 
 
- In calling thread at line 1 we created a thread object.
- On Line 2 we started the thread t.
- Then on line 3 we are calling Join() method of Thread t which serves the other way around. 
   I mean if you think logically t.Join() causes the calling thread to wait untill thread T  completes.
   The join() method is a busy waiting technique… i.e. The main thread is engaged in a continuous
   loop checking for thread t.IsAlive property to be false. t.Join() syntax is also an invalidation of an
   important OOP concept, “Encapsulation”… i.e. in t.Join() we are actually blocking Main thread
   instead of working on Thread t.
 
I don’t know how many of you agree that logically it should be the other way around (i.e. One
should be calling Thread.CurrentThread.Join(t) instead of t.Join()).
 
Any one thinks of a reason why the Thread.Join() method was implemented like this??