开发者

C# creating common instance

My question is why does this line - Thread开发者_开发百科Test 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"


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.


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!


6 years later and I'm here because I read the same section of that book. The example in the book immediately previous to the one you mentioned shows (a static) .Go being executed on an anonymous new thread, and then again separately in the local context.

new Thread (Go).Start();
Go();

The example in your question first creates an instance of the TT and also changes .Go from being a static method to an instance method.

ThreadTest tt = new ThreadTest();
new Thread (tt.Go).Start();
tt.Go();

So now when .Go is sent to the new thread for execution, what is getting sent is tt's copy of the method (instead of a static .Go method), which is also what gets executed locally immediately afterwards on line 3. Since both executions of .Go belong to tt, they also use tt's copy of done. Afaik, this is why the author calls this data "common", because it can now be accessed by both threads.

Aside: I'm still shaky on several aspects of threading myself. One mystery to me is what exactly happens to tt when new Thread (tt.Go).Start(); executes... tt was instantiated in the initial thread, but it now lives in both? Does byref/byval apply here or is something else going on? Is it more accurate to say that the tt object doesn't actually 'live' or 'belong to' either thread, but rather on the heap, and therefore both threads should have access to it?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜