[Mono-list] Threading

Dick Porter dick@ximian.com
Mon, 13 May 2002 15:20:13 +0100

On Mon, May 13, 2002 at 09:41:37AM -0400, Ian McCullough wrote:
> >
> > It will if you run it enough times...
> >
> > Basically, sometimes Main() exits before DoThread() gets going.  It should
> > be waiting for the thread that was started.
> >
> > Please bugzilla this.
> Hold up a sec! If I'm correct, this behavior is "By Design."  If you want
> the main thread of execution to wait for the other one, you must tell it to.
> The simplest way to do this would be to modify TestThread() to be like this:

No, the subthread has been created, but the runtime hasn't squirreled away
the fact that its there before Main() exits.  That's the broken part.

> treated as such.  You can also use any number of other synchronization
> primitives, but essentially, unless the main thread is explicitly waiting
> for the other thread, there is a chance that the death of the main thread
> immediately upon return from the TestThread() call will cause the death of
> the thread before it gets a chance to send stuff to the console.  When the
> main thread of execution dies it takes all the others with it, forcibly.

Not true, if you examine the ms runtime behaviour.  The main thread implicitly
Join()s all other threads as it exits.

Try this:

using System;
using System.Threading;

public class Test {
	private void Thread_func() {
		Console.WriteLine("In a thread!");
		Console.WriteLine("Subthread finished sleeping");
	public static int Main () {
		Thread thr=new Thread(new ThreadStart(new Test().Thread_func));
		Console.WriteLine("In the main line!");
		return 0;

- Dick