dotgnu-pnet
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Pnet-developers] Thread.Join and the main thread


From: Thong (Tum) Nguyen
Subject: [Pnet-developers] Thread.Join and the main thread
Date: Thu, 20 May 2004 05:38:10 +1200

Hi Rhys,

I've come up with a design problem with I thought I might pass by you.

Currently, the main system thread (what you get when you call ILThreadSelf()
from main()) is also the main CLR thread in multi threaded systems.
Consider the following application:

using System;
using System.Threading;

public class Test
{
        static Thread mainThread;
        
        public static void Run()
        {
                mainThread.Join();
        }
        
        public static void Main()
        {
                mainThread = Thread.CurrentThread;
                
                Thread thread = new Thread(new ThreadStart(Run));
                
                thread.Start();
        }
}

To me, the program should finish because the main thread will exit from
Test.Main allowing the thread inside Test.Run exit the join.

The problem we currently have is that the thread which calls Test.Main is
the same thread that waits for foreground threads to finish at the end of
the program and the thread in Test.Run is waiting for the thread in
Test.Main to finish!  Deadlock!

I can see two obvious solutions.  Solution 1 is for ilrun to create a new
thread for Main to run under (not the main system thread).  That way, the
thread which executes the program entry point won't be the thread which ends
up waiting for foreground threads to finish.  Solution 2 is to allow the
ilrun's main to call some new method (ILThreadMainFinished?) after the
program's entry point has been called but before it waits on all foreground
threads to finish.  The method would cause all threads waiting to join on
the main system thread to exit.

Solution 1 seems cleanest and lest hackish to me (by far) but does require
that even the simplest of programs (on multithreaded profiles) to have two
threads (three if you include the finalizer thread).  What do you think?

PS.  MS.NET seems to deadlock but both Mono and Sun's JVM (1.4) do not.  I
think the behaviour displayed by both Mono and Java is the expected and
correct behaviour.

Regards,

^Tum



reply via email to

[Prev in Thread] Current Thread [Next in Thread]