New test.
[mono.git] / mono / metadata / threads.c
index 533209938993653d1ba43cfa1f959038cd8f5e5c..dfbe2f24ddedc3857b43fbd83b7d4aba8faf9209 100644 (file)
@@ -133,7 +133,7 @@ static MonoThreadStartCB mono_thread_start_cb = NULL;
 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
 
 /* function called at thread cleanup */
-static MonoThreadCleanupFunc mono_thread_cleanup = NULL;
+static MonoThreadCleanupFunc mono_thread_cleanup_fn = NULL;
 
 /* The default stack size for each thread */
 static guint32 default_stacksize = 0;
@@ -144,6 +144,7 @@ static void mono_init_static_data_info (StaticDataInfo *static_data);
 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
 static gboolean mono_thread_resume (MonoThread* thread);
 static void mono_thread_start (MonoThread *thread);
+static void signal_thread_state_change (MonoThread *thread);
 
 /* Spin lock for InterlockedXXX 64 bit functions */
 #define mono_interlocked_lock() EnterCriticalSection (&interlocked_mutex)
@@ -242,8 +243,8 @@ static void thread_cleanup (MonoThread *thread)
 
        thread->cached_culture_info = NULL;
 
-       if (mono_thread_cleanup)
-               mono_thread_cleanup (thread);
+       if (mono_thread_cleanup_fn)
+               mono_thread_cleanup_fn (thread);
 }
 
 static guint32 WINAPI start_wrapper(void *data)
@@ -251,7 +252,7 @@ static guint32 WINAPI start_wrapper(void *data)
        struct StartInfo *start_info=(struct StartInfo *)data;
        guint32 (*start_func)(void *);
        void *start_arg;
-       guint32 tid;
+       gsize tid;
        MonoThread *thread=start_info->obj;
        MonoObject *start_delegate = start_info->delegate;
 
@@ -307,7 +308,7 @@ static guint32 WINAPI start_wrapper(void *data)
                   thread->tid);
 #endif
 
-       /* start_func is set only for unamanged start functions */
+       /* start_func is set only for unmanaged start functions */
        if (start_func) {
                start_func (start_arg);
        } else {
@@ -325,6 +326,8 @@ static guint32 WINAPI start_wrapper(void *data)
 
        THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper terminating", __func__, GetCurrentThreadId ()));
 
+       thread_cleanup (thread);
+
        /* Remove the reference to the thread object in the TLS data,
         * so the thread object can be finalized.  This won't be
         * reached if the thread threw an uncaught exception, so those
@@ -335,8 +338,6 @@ static guint32 WINAPI start_wrapper(void *data)
         */
        SET_CURRENT_OBJECT (NULL);
 
-       thread_cleanup (thread);
-
        return(0);
 }
 
@@ -457,10 +458,11 @@ mono_thread_detach (MonoThread *thread)
        g_return_if_fail (thread != NULL);
 
        THREAD_DEBUG (g_message ("%s: mono_thread_detach for %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
-       SET_CURRENT_OBJECT (NULL);
        
        thread_cleanup (thread);
 
+       SET_CURRENT_OBJECT (NULL);
+
        /* Don't need to CloseHandle this thread, even though we took a
         * reference in mono_thread_attach (), because the GC will do it
         * when the Thread object is finalised.
@@ -472,8 +474,8 @@ mono_thread_exit ()
 {
        MonoThread *thread = mono_thread_current ();
 
-       SET_CURRENT_OBJECT (NULL);
        thread_cleanup (thread);
+       SET_CURRENT_OBJECT (NULL);
 
        /* we could add a callback here for embedders to use. */
        if (thread == mono_thread_get_main ())
@@ -599,6 +601,8 @@ void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
 
        THREAD_DEBUG (g_message ("%s: Sleeping for %d ms", __func__, ms));
 
+       mono_thread_current_check_pending_interrupt ();
+       
        mono_monitor_enter (thread->synch_lock);
        thread->state |= ThreadState_WaitSleepJoin;
        mono_monitor_exit (thread->synch_lock);
@@ -610,6 +614,18 @@ void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
        mono_monitor_exit (thread->synch_lock);
 }
 
+void ves_icall_System_Threading_Thread_SpinWait_internal (gint32 iterations)
+{
+       gint32 i;
+       
+       for(i = 0; i < iterations; i++) {
+               /* We're busy waiting, but at least we can tell the
+                * scheduler to let someone else have a go...
+                */
+               Sleep (0);
+       }
+}
+
 gint32
 ves_icall_System_Threading_Thread_GetDomainID (void) 
 {
@@ -813,6 +829,8 @@ gboolean ves_icall_System_Threading_Thread_Join_internal(MonoThread *this,
                return FALSE;
        }
        
+       mono_thread_current_check_pending_interrupt ();
+       
        this->state |= ThreadState_WaitSleepJoin;
        mono_monitor_exit (this->synch_lock);
 
@@ -851,6 +869,9 @@ gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_
                
        MONO_ARCH_SAVE_REGS;
 
+       /* Do this WaitSleepJoin check before creating objects */
+       mono_thread_current_check_pending_interrupt ();
+
        numhandles = mono_array_length(mono_handles);
        handles = g_new0(HANDLE, numhandles);
 
@@ -910,6 +931,9 @@ gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_ha
                
        MONO_ARCH_SAVE_REGS;
 
+       /* Do this WaitSleepJoin check before creating objects */
+       mono_thread_current_check_pending_interrupt ();
+
        numhandles = mono_array_length(mono_handles);
        handles = g_new0(HANDLE, numhandles);
 
@@ -970,6 +994,8 @@ gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this
                ms=INFINITE;
        }
        
+       mono_thread_current_check_pending_interrupt ();
+
        mono_monitor_enter (thread->synch_lock);
        thread->state |= ThreadState_WaitSleepJoin;
        mono_monitor_exit (thread->synch_lock);
@@ -1455,6 +1481,47 @@ ves_icall_System_Threading_Thread_GetState (MonoThread* this)
        return state;
 }
 
+void ves_icall_System_Threading_Thread_Interrupt_internal (MonoThread *this)
+{
+       gboolean throw = FALSE;
+       
+       mono_monitor_enter (this->synch_lock);
+       
+       /* Clear out any previous request */
+       this->thread_interrupt_requested = FALSE;
+       
+       if (this->state & ThreadState_WaitSleepJoin) {
+               throw = TRUE;
+       } else {
+               this->thread_interrupt_requested = TRUE;
+       }
+       
+       mono_monitor_exit (this->synch_lock);
+
+       if (throw) {
+               signal_thread_state_change (this);
+       }
+}
+
+void mono_thread_current_check_pending_interrupt ()
+{
+       MonoThread *thread = mono_thread_current ();
+       gboolean throw = FALSE;
+       
+       mono_monitor_enter (thread->synch_lock);
+
+       if (thread->thread_interrupt_requested) {
+               throw = TRUE;
+               thread->thread_interrupt_requested = FALSE;
+       }
+       
+       mono_monitor_exit (thread->synch_lock);
+
+       if (throw) {
+               mono_raise_exception (mono_get_exception_thread_interrupted ());
+       }
+}
+
 int  
 mono_thread_get_abort_signal (void)
 {
@@ -1636,6 +1703,10 @@ mono_thread_resume (MonoThread *thread)
        }
        
        thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
+       if (thread->resume_event == NULL) {
+               mono_monitor_exit (thread->synch_lock);
+               return(FALSE);
+       }
        
        /* Awake the thread */
        SetEvent (thread->suspend_event);
@@ -1770,6 +1841,7 @@ void mono_thread_init (MonoThreadStartCB start_cb,
        InitializeCriticalSection(&interlocked_mutex);
        InitializeCriticalSection(&contexts_mutex);
        background_change_event = CreateEvent (NULL, TRUE, FALSE, NULL);
+       g_assert(background_change_event != NULL);
        
        mono_init_static_data_info (&thread_static_info);
        mono_init_static_data_info (&context_static_info);
@@ -1788,10 +1860,40 @@ void mono_thread_init (MonoThreadStartCB start_cb,
        GetCurrentProcess ();
 }
 
+void mono_thread_cleanup (void)
+{
+#if !defined(PLATFORM_WIN32) && !defined(RUN_IN_SUBTHREAD)
+       /* The main thread must abandon any held mutexes (particularly
+        * important for named mutexes as they are shared across
+        * processes, see bug 74680.)  This will happen when the
+        * thread exits, but if it's not running in a subthread it
+        * won't exit in time.
+        */
+       /* Using non-w32 API is a nasty kludge, but I couldn't find
+        * anything in the documentation that would let me do this
+        * here yet still be safe to call on windows.
+        */
+       _wapi_thread_signal_self (mono_environment_exitcode_get ());
+#endif
+
+#if 0
+       /* This stuff needs more testing, it seems one of these
+        * critical sections can be locked when mono_thread_cleanup is
+        * called.
+        */
+       DeleteCriticalSection (&threads_mutex);
+       DeleteCriticalSection (&interlocked_mutex);
+       DeleteCriticalSection (&contexts_mutex);
+       CloseHandle (background_change_event);
+#endif
+
+       TlsFree (current_object_key);
+}
+
 void
 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
 {
-       mono_thread_cleanup = func;
+       mono_thread_cleanup_fn = func;
 }
 
 G_GNUC_UNUSED
@@ -1907,27 +2009,38 @@ static void build_wait_tids (gpointer key, gpointer value, gpointer user)
                /* Ignore background threads, we abort them later */
                mono_monitor_enter (thread->synch_lock);
                if (thread->state & ThreadState_Background) {
+                       THREAD_DEBUG (g_message ("%s: ignoring background thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
                        mono_monitor_exit (thread->synch_lock);
                        return; /* just leave, ignore */
                }
                mono_monitor_exit (thread->synch_lock);
                
-               if (mono_gc_is_finalizer_thread (thread))
+               if (mono_gc_is_finalizer_thread (thread)) {
+                       THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
                        return;
+               }
 
-               if (thread == mono_thread_current ())
+               if (thread == mono_thread_current ()) {
+                       THREAD_DEBUG (g_message ("%s: ignoring current thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
                        return;
+               }
 
-               if (thread == mono_thread_get_main ())
+               if (thread == mono_thread_get_main ()) {
+                       THREAD_DEBUG (g_message ("%s: ignoring main thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
                        return;
+               }
 
                handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
-               if (handle == NULL)
+               if (handle == NULL) {
+                       THREAD_DEBUG (g_message ("%s: ignoring unopenable thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
                        return;
+               }
                
                wait->handles[wait->num]=handle;
                wait->threads[wait->num]=thread;
                wait->num++;
+
+               THREAD_DEBUG (g_message ("%s: adding thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
        } else {
                /* Just ignore the rest, we can't do anything with
                 * them yet
@@ -2026,20 +2139,6 @@ void mono_thread_manage (void)
                        wait_for_tids (wait, INFINITE);
                }
        } while (wait->num > 0);
-
-#if !defined(PLATFORM_WIN32) && !defined(RUN_IN_SUBTHREAD)
-       /* The main thread must abandon any held mutexes (particularly
-        * important for named mutexes as they are shared across
-        * processes, see bug 74680.)  This will happen when the
-        * thread exits, but if it's not running in a subthread it
-        * won't exit in time.
-        */
-       /* Using non-w32 API is a nasty kludge, but I couldn't find
-        * anything in the documentation that would let me do this
-        * here yet still be safe to call on windows.
-        */
-       _wapi_thread_abandon_mutexes (NULL);
-#endif
        
        /* 
         * give the subthreads a chance to really quit (this is mainly needed
@@ -2145,8 +2244,14 @@ void mono_thread_suspend_all_other_threads (void)
                        
                thread->state |= ThreadState_SuspendRequested;
 
-               if (thread->suspended_event == NULL)
+               if (thread->suspended_event == NULL) {
                        thread->suspended_event = CreateEvent (NULL, TRUE, FALSE, NULL);
+                       if (thread->suspended_event == NULL) {
+                               /* Forget this one and go on to the next */
+                               mono_monitor_exit (thread->synch_lock);
+                               continue;
+                       }
+               }
 
                events [eventidx++] = thread->suspended_event;
                mono_monitor_exit (thread->synch_lock);
@@ -2658,6 +2763,10 @@ static MonoException* mono_thread_execute_interruption (MonoThread *thread)
                thread->state &= ~ThreadState_SuspendRequested;
                thread->state |= ThreadState_Suspended;
                thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
+               if (thread->suspend_event == NULL) {
+                       mono_monitor_exit (thread->synch_lock);
+                       return(NULL);
+               }
                if (thread->suspended_event)
                        SetEvent (thread->suspended_event);
                mono_monitor_exit (thread->synch_lock);
@@ -2681,6 +2790,9 @@ static MonoException* mono_thread_execute_interruption (MonoThread *thread)
                mono_monitor_exit (thread->synch_lock);
                mono_thread_exit ();
                return NULL;
+       } else if (thread->thread_interrupt_requested) {
+               mono_monitor_exit (thread->synch_lock);
+               return(mono_get_exception_thread_interrupted ());
        }
        
        mono_monitor_exit (thread->synch_lock);