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”
It is unclear what you mean by “common instance”, but the constructor definitely creates a new instance. The
Gomethod 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
Gomethod on the same instance.The inside of the
Gomethod has a race condition. It may unpredictably print “Done” twice.