I was looking at the Microsoft MSDN reference page regarding the modifier “volatile”, and was a little unsure as to the way in which the snippet they provided, waited for a thread to complete execution.
I know it is only example code, and that the thread completed very quickly, but I believe that the code below is not very good for developers trying to understand threading.
I believe Microsoft have actually presented a code snippet which will introduce a “tight-loop” in the code. Now I appreciate that it will not affect this code snippet (that much), but if a developer takes this code and tries to use it for some multi-threaded code that is a little more intensive, I would presume the “tight-loop” issue would arise?
using System;
using System.Threading;
class Test
{
public static int result;
public static volatile bool finished;
static void Thread2() {
result = 143;
finished = true;
}
static void Main() {
finished = false;
// Run Thread2() in a new thread
new Thread(new ThreadStart(Thread2)).Start();
// Wait for Thread2 to signal that it has a result by setting
// finished to true.
for (;;) {
if (finished) {
Console.WriteLine("result = {0}", result);
return;
}
}
}
}
Snippet reference:
http://msdn.microsoft.com/en-gb/library/aa645755(v=vs.71).aspx
What would be the better way to wait for the thread to finish, in the example above, which would not introduce this “tight-loop” situation?
Or, will a “tight-loop” not actually be introduced at all?
Please note, that the purpose of the snippet is to demonstrate the “volatile” keyword, so using a Thread.Join() would take the snippet out of context I believe.
This snippet doesn’t illustrate how to wait, this just illustrates access to a
volatilefield from different threads.To wait for your background thread simply, you can use this snippet: