tags:

views:

69

answers:

2

My question is why does this line - ThreadTest tt = new ThreadTest(); in below example create a common instance not a separate instance. Please advise, thanks!

class ThreadTest
{
  bool done;

  static void Main()
  {
    ThreadTest tt = new ThreadTest();   // Create a common instance
    new Thread (tt.Go).Start();
    tt.Go();
  }

  // Note that Go is now an instance method
  void Go() 
  {
     if (!done) { done = true; Console.WriteLine ("Done"); }
  }
}

EDIT: The example is from http://www.albahari.com/threading/#_Introduction which demonstrates how to share data between threads.

EDIT2: My question is exactly why "the instance is common to both threads"

+3  A: 

It is unclear what you mean by “common instance”, but the constructor definitely creates a new instance. The Go method is executed twice, once in the new thread and once in the main thread.

Maybe what the author of the code meant is that the instance is common to both threads, because both threads call the Go method on the same instance.

The inside of the Go method has a race condition. It may unpredictably print “Done” twice.

Timwi
@Timwi: your guess is right. However, my question is exactly why "the instance is common to both threads".
Stan
Because you’re creating only one and using it twice.
Timwi
Ah, I thought it was likenew Thread (tt.Go).Start(); Go();
Stan
A: 

If you mean that both calls to tt.Go share the 'done' variable, then that will of course happen. You are calling a method on the same object, just that one happens in the main thread, and one happens in a separate thread.

You only ever create one instance of ThreadTest, but call Go twice, so both calls have to happen on the same object!

Kazar