New test.
[mono.git] / mono / metadata / threads.c
index 48384353a5801064db99eafdb8289ddbf2d2faf7..dfbe2f24ddedc3857b43fbd83b7d4aba8faf9209 100644 (file)
@@ -31,6 +31,7 @@
 #include <mono/metadata/marshal.h>
 #include <mono/io-layer/io-layer.h>
 #include <mono/metadata/object-internals.h>
+#include <mono/metadata/mono-debug-debugger.h>
 #include <mono/utils/mono-compiler.h>
 
 #include <mono/os/gc_wrapper.h>
 /*#define LIBGC_DEBUG(a) do { a; } while (0)*/
 #define LIBGC_DEBUG(a)
 
+/* Provide this for systems with glib < 2.6 */
+#ifndef G_GSIZE_FORMAT
+#   if GLIB_SIZEOF_LONG == 8
+#       define G_GSIZE_FORMAT "lu"
+#   else
+#       define G_GSIZE_FORMAT "u"
+#   endif
+#endif
+
 struct StartInfo 
 {
        guint32 (*func)(void *);
@@ -66,8 +76,13 @@ typedef struct {
        int offset;
 } StaticDataInfo;
 
-/* Number of cached culture objects in the MonoThread->culture_info array */
+/* Number of cached culture objects in the MonoThread->cached_culture_info array
+ * (per-type): we use the first NUM entries for CultureInfo and the last for
+ * UICultureInfo. So the size of the array is really NUM_CACHED_CULTURES * 2.
+ */
 #define NUM_CACHED_CULTURES 4
+#define CULTURES_START_IDX 0
+#define UICULTURES_START_IDX NUM_CACHED_CULTURES
 
 /*
  * The "os_handle" field of the WaitHandle class.
@@ -75,9 +90,13 @@ typedef struct {
 static MonoClassField *wait_handle_os_handle_field = NULL;
 
 /* Controls access to the 'threads' hash table */
+#define mono_threads_lock() EnterCriticalSection (&threads_mutex)
+#define mono_threads_unlock() LeaveCriticalSection (&threads_mutex)
 static CRITICAL_SECTION threads_mutex;
 
 /* Controls access to context static data */
+#define mono_contexts_lock() EnterCriticalSection (&contexts_mutex)
+#define mono_contexts_unlock() LeaveCriticalSection (&contexts_mutex)
 static CRITICAL_SECTION contexts_mutex;
 
 /* Holds current status of static data heap */
@@ -114,10 +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;
-
-/* function called when a new thread has been created */
-static MonoThreadCallbacks *mono_thread_callbacks = NULL;
+static MonoThreadCleanupFunc mono_thread_cleanup_fn = NULL;
 
 /* The default stack size for each thread */
 static guint32 default_stacksize = 0;
@@ -128,8 +144,11 @@ 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)
+#define mono_interlocked_unlock() LeaveCriticalSection (&interlocked_mutex)
 static CRITICAL_SECTION interlocked_mutex;
 
 /* global count of thread interruptions requested */
@@ -157,9 +176,9 @@ mono_thread_get_tls_offset (void)
  */
 static void handle_store(MonoThread *thread)
 {
-       EnterCriticalSection(&threads_mutex);
+       mono_threads_lock ();
 
-       THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": thread %p ID %"G_GSIZE_FORMAT, thread, (gsize)thread->tid));
+       THREAD_DEBUG (g_message ("%s: thread %p ID %"G_GSIZE_FORMAT, __func__, thread, (gsize)thread->tid));
 
        if(threads==NULL) {
                MONO_GC_REGISTER_ROOT (threads);
@@ -171,19 +190,21 @@ static void handle_store(MonoThread *thread)
         */
        mono_g_hash_table_insert(threads, (gpointer)(gsize)(thread->tid),
                                 thread);
-       LeaveCriticalSection(&threads_mutex);
+
+       mono_threads_unlock ();
 }
 
 static void handle_remove(gsize tid)
 {
-       THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": thread ID %"G_GSIZE_FORMAT, tid));
+       THREAD_DEBUG (g_message ("%s: thread ID %"G_GSIZE_FORMAT, __func__, tid));
 
-       EnterCriticalSection(&threads_mutex);
+       mono_threads_lock ();
+       
 
        if (threads)
                mono_g_hash_table_remove (threads, (gpointer)tid);
        
-       LeaveCriticalSection(&threads_mutex);
+       mono_threads_unlock ();
 
        /* Don't close the handle here, wait for the object finalizer
         * to do it. Otherwise, the following race condition applies:
@@ -203,7 +224,7 @@ static void handle_remove(gsize tid)
 static void thread_cleanup (MonoThread *thread)
 {
        g_assert (thread != NULL);
-       
+
        mono_release_type_locks (thread);
 
        if (!mono_monitor_enter (thread->synch_lock))
@@ -220,11 +241,10 @@ static void thread_cleanup (MonoThread *thread)
        if (thread->serialized_culture_info)
                g_free (thread->serialized_culture_info);
 
-       mono_gc_free_fixed (thread->culture_info);
-       mono_gc_free_fixed (thread->ui_culture_info);
+       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)
@@ -232,12 +252,12 @@ 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;
 
-       THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%"G_GSIZE_FORMAT") Start wrapper", GetCurrentThreadId ()));
-       
+       THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper", __func__, GetCurrentThreadId ()));
+
        /* We can be sure start_info->obj->tid and
         * start_info->obj->handle have been set, because the thread
         * was created suspended, and these values were set before the
@@ -264,13 +284,9 @@ static guint32 WINAPI start_wrapper(void *data)
        mono_thread_new_init (tid, &tid, start_func);
        thread->stack_ptr = &tid;
 
-       LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
-                  ": (%"G_GSIZE_FORMAT",%d) Setting thread stack to %p",
-                  GetCurrentThreadId (), getpid (), thread->stack_ptr));
+       LIBGC_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT",%d) Setting thread stack to %p", __func__, GetCurrentThreadId (), getpid (), thread->stack_ptr));
 
-       THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
-                  ": (%"G_GSIZE_FORMAT") Setting current_object_key to %p",
-                  GetCurrentThreadId (), thread));
+       THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
 
        mono_profiler_thread_start (tid);
 
@@ -288,11 +304,11 @@ static guint32 WINAPI start_wrapper(void *data)
 
        thread_adjust_static_data (thread);
 #ifdef DEBUG
-       g_message (G_GNUC_PRETTY_FUNCTION "start_wrapper for %"G_GSIZE_FORMAT,
+       g_message ("%s: start_wrapper for %"G_GSIZE_FORMAT, __func__,
                   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 {
@@ -308,7 +324,9 @@ static guint32 WINAPI start_wrapper(void *data)
         * call thread_cleanup() on this thread's behalf.
         */
 
-       THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%"G_GSIZE_FORMAT") Start wrapper terminating", GetCurrentThreadId ()));
+       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
@@ -320,8 +338,6 @@ static guint32 WINAPI start_wrapper(void *data)
         */
        SET_CURRENT_OBJECT (NULL);
 
-       thread_cleanup (thread);
-
        return(0);
 }
 
@@ -330,9 +346,6 @@ void mono_thread_new_init (gsize tid, gpointer stack_start, gpointer func)
        if (mono_thread_start_cb) {
                mono_thread_start_cb (tid, stack_start, func);
        }
-
-       if (mono_thread_callbacks)
-               (* mono_thread_callbacks->thread_created) (tid, stack_start, func);
 }
 
 void mono_threads_set_default_stacksize (guint32 stacksize)
@@ -351,7 +364,7 @@ void mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
        HANDLE thread_handle;
        struct StartInfo *start_info;
        gsize tid;
-       
+
        thread=(MonoThread *)mono_object_new (domain,
                                              mono_defaults.thread_class);
 
@@ -366,8 +379,7 @@ void mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
         */
        thread_handle = CreateThread(NULL, default_stacksize_for_thread (thread), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
                                     CREATE_SUSPENDED, &tid);
-       THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Started thread ID %"G_GSIZE_FORMAT" (handle %p)",
-                 tid, thread_handle));
+       THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
        if (thread_handle == NULL) {
                /* The thread couldn't be created, so throw an exception */
                mono_raise_exception (mono_get_exception_execution_engine ("Couldn't create thread"));
@@ -377,7 +389,7 @@ void mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
        thread->handle=thread_handle;
        thread->tid=tid;
 
-       thread->synch_lock=mono_object_new (domain, mono_defaults.object_class);
+       MONO_OBJECT_SETREF (thread, synch_lock, mono_object_new (domain, mono_defaults.object_class));
                                                  
        handle_store(thread);
 
@@ -392,12 +404,14 @@ mono_thread_attach (MonoDomain *domain)
        gsize tid;
 
        if ((thread = mono_thread_current ())) {
+               if (domain != mono_domain_get ())
+                       mono_domain_set (domain, TRUE);
                /* Already attached */
                return thread;
        }
 
        if (!mono_gc_register_thread (&domain)) {
-               g_error ("Thread %p calling into managed code is not registered with the GC. On UNIX, this can be fixed by #include-ing <gc.h> before <pthread.h> in the file containing the thread creation code.", GetCurrentThread ());
+               g_error ("Thread %"G_GSIZE_FORMAT" calling into managed code is not registered with the GC. On UNIX, this can be fixed by #include-ing <gc.h> before <pthread.h> in the file containing the thread creation code.", GetCurrentThreadId ());
        }
 
        thread = (MonoThread *)mono_object_new (domain,
@@ -408,26 +422,23 @@ mono_thread_attach (MonoDomain *domain)
 
        tid=GetCurrentThreadId ();
 
-#ifdef PLATFORM_WIN32
        /* 
         * The handle returned by GetCurrentThread () is a pseudo handle, so it can't be used to
         * refer to the thread from other threads for things like aborting.
         */
        DuplicateHandle (GetCurrentProcess (), thread_handle, GetCurrentProcess (), &thread_handle, 
                                         THREAD_ALL_ACCESS, TRUE, 0);
-#endif
 
        thread->handle=thread_handle;
        thread->tid=tid;
-       thread->synch_lock=mono_object_new (domain, mono_defaults.object_class);
+       thread->stack_ptr = &tid;
+       MONO_OBJECT_SETREF (thread, synch_lock, mono_object_new (domain, mono_defaults.object_class));
 
-       THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Attached thread ID %"G_GSIZE_FORMAT" (handle %p)",
-                 tid, thread_handle));
+       THREAD_DEBUG (g_message ("%s: Attached thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
 
        handle_store(thread);
 
-       THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%"G_GSIZE_FORMAT") Setting current_object_key to %p",
-                  GetCurrentThreadId (), thread));
+       THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
 
        SET_CURRENT_OBJECT (thread);
        mono_domain_set (domain, TRUE);
@@ -446,10 +457,16 @@ mono_thread_detach (MonoThread *thread)
 {
        g_return_if_fail (thread != NULL);
 
-       THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION "mono_thread_detach for %"G_GSIZE_FORMAT, thread->tid));
-       SET_CURRENT_OBJECT (NULL);
+       THREAD_DEBUG (g_message ("%s: mono_thread_detach for %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
        
        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.
+        */
 }
 
 void
@@ -457,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 ())
@@ -476,8 +493,7 @@ HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
        
        MONO_ARCH_SAVE_REGS;
 
-       THREAD_DEBUG (g_message(G_GNUC_PRETTY_FUNCTION
-                 ": Trying to start a new thread: this (%p) start (%p)", this, start));
+       THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p) start (%p)", __func__, this, start));
 
        mono_monitor_enter (this->synch_lock);
 
@@ -496,7 +512,7 @@ HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
                /* This is freed in start_wrapper */
                start_info = g_new0 (struct StartInfo, 1);
                start_info->func = start_func;
-               start_info->start_arg = this->start_obj;
+               start_info->start_arg = this->start_obj; /* FIXME: GC object stored in unmanaged memory */
                start_info->delegate = start;
                start_info->obj = this;
                start_info->domain = mono_domain_get ();
@@ -504,7 +520,7 @@ HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
                this->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
                if(this->start_notify==NULL) {
                        mono_monitor_exit (this->synch_lock);
-                       g_warning (G_GNUC_PRETTY_FUNCTION ": CreateSemaphore error 0x%x", GetLastError ());
+                       g_warning ("%s: CreateSemaphore error 0x%x", __func__, GetLastError ());
                        return(NULL);
                }
 
@@ -512,8 +528,7 @@ HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
                                    CREATE_SUSPENDED, &tid);
                if(thread==NULL) {
                        mono_monitor_exit (this->synch_lock);
-                       g_warning(G_GNUC_PRETTY_FUNCTION
-                                 ": CreateThread error 0x%x", GetLastError());
+                       g_warning("%s: CreateThread error 0x%x", __func__, GetLastError());
                        return(NULL);
                }
                
@@ -530,7 +545,7 @@ HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
                
                this->state &= ~ThreadState_Unstarted;
 
-               THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Started thread ID %"G_GSIZE_FORMAT" (handle %p)", tid, thread));
+               THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread));
 
                mono_monitor_exit (this->synch_lock);
                return(thread);
@@ -542,7 +557,7 @@ void ves_icall_System_Threading_Thread_Thread_free_internal (MonoThread *this,
 {
        MONO_ARCH_SAVE_REGS;
 
-       THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Closing thread %p, handle %p", this, thread));
+       THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__, this, thread));
 
        CloseHandle (thread);
 }
@@ -551,7 +566,7 @@ static void mono_thread_start (MonoThread *thread)
 {
        MONO_ARCH_SAVE_REGS;
 
-       THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%"G_GSIZE_FORMAT") Launching thread %p (%"G_GSIZE_FORMAT")", GetCurrentThreadId (), thread, (gsize)thread->tid));
+       THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
 
        /* Only store the handle when the thread is about to be
         * launched, to avoid the main thread deadlocking while trying
@@ -559,14 +574,8 @@ static void mono_thread_start (MonoThread *thread)
         */
        handle_store (thread);
 
-       if (mono_thread_callbacks)
-               (* mono_thread_callbacks->start_resume) (thread->tid);
-
        ResumeThread (thread->handle);
 
-       if (mono_thread_callbacks)
-               (* mono_thread_callbacks->end_resume) (thread->tid);
-
        if(thread->start_notify!=NULL) {
                /* Wait for the thread to set up its TLS data etc, so
                 * theres no potential race condition if someone tries
@@ -574,14 +583,14 @@ static void mono_thread_start (MonoThread *thread)
                 * started
                 */
 
-               THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%"G_GSIZE_FORMAT") waiting for thread %p (%"G_GSIZE_FORMAT") to start", GetCurrentThreadId (), thread, (gsize)thread->tid));
+               THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for thread %p (%"G_GSIZE_FORMAT") to start", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
 
                WaitForSingleObjectEx (thread->start_notify, INFINITE, FALSE);
                CloseHandle (thread->start_notify);
                thread->start_notify = NULL;
        }
 
-       THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%"G_GSIZE_FORMAT") Done launching thread %p (%"G_GSIZE_FORMAT")", GetCurrentThreadId (), thread, (gsize)thread->tid));
+       THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Done launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
 }
 
 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
@@ -590,8 +599,10 @@ void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
        
        MONO_ARCH_SAVE_REGS;
 
-       THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Sleeping for %d ms", 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);
@@ -603,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) 
 {
@@ -647,18 +670,16 @@ ves_icall_System_Threading_Thread_SetName_internal (MonoThread *this_obj, MonoSt
        mono_monitor_exit (this_obj->synch_lock);
 }
 
-MonoObject*
-ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoThread *this)
+static MonoObject*
+lookup_cached_culture (MonoThread *this, MonoDomain *domain, int start_idx)
 {
        MonoObject *res;
-       MonoDomain *domain;
        int i;
 
-       /* No need to lock here */
-       if (this->culture_info) {
+       if (this->cached_culture_info) {
                domain = mono_domain_get ();
-               for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
-                       res = this->culture_info [i];
+               for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
+                       res = mono_array_get (this->cached_culture_info, MonoObject*, i);
                        if (res && res->vtable->domain == domain)
                                return res;
                }
@@ -667,6 +688,12 @@ ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoThread *this)
        return NULL;
 }
 
+MonoObject*
+ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoThread *this)
+{
+       return lookup_cached_culture (this, mono_domain_get (), CULTURES_START_IDX);
+}
+
 MonoArray*
 ves_icall_System_Threading_Thread_GetSerializedCurrentCulture (MonoThread *this)
 {
@@ -676,40 +703,55 @@ ves_icall_System_Threading_Thread_GetSerializedCurrentCulture (MonoThread *this)
        if (this->serialized_culture_info) {
                res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_culture_info_len);
                memcpy (mono_array_addr (res, guint8, 0), this->serialized_culture_info, this->serialized_culture_info_len);
-       }
-       else
+       } else {
                res = NULL;
+       }
        mono_monitor_exit (this->synch_lock);
 
        return res;
 }
 
-void
-ves_icall_System_Threading_Thread_SetCachedCurrentCulture (MonoThread *this, MonoObject *culture)
+static void
+cache_culture (MonoThread *this, MonoObject *culture, int start_idx)
 {
        int i;
        MonoDomain *domain = mono_domain_get ();
+       MonoObject *obj;
+       int free_slot = -1;
+       int same_domain_slot = -1;
 
        mono_monitor_enter (this->synch_lock);
-       if (!this->culture_info) {
-               this->culture_info = mono_gc_alloc_fixed (sizeof (MonoObject*) * NUM_CACHED_CULTURES, NULL);
-       }
-
-       for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
-               if (this->culture_info [i]) {
-                       if (this->culture_info [i]->vtable->domain == domain)
-                               /* Replace */
-                               break;
+       if (!this->cached_culture_info)
+               this->cached_culture_info = mono_array_new (mono_object_domain (this), mono_defaults.object_class, NUM_CACHED_CULTURES * 2);
+
+       for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
+               obj = mono_array_get (this->cached_culture_info, MonoObject*, i);
+               /* Free entry */
+               if (!obj) {
+                       free_slot = i;
+                       /* we continue, because there may be a slot used with the same domain */
+                       continue;
                }
-               else
-                       /* Free entry */
+               /* Replace */
+               if (obj->vtable->domain == domain) {
+                       same_domain_slot = i;
                        break;
+               }
        }
-       if (i < NUM_CACHED_CULTURES)
-               this->culture_info [i] = culture;
+       if (same_domain_slot >= 0)
+               mono_array_setref (this->cached_culture_info, same_domain_slot, culture);
+       else if (free_slot >= 0)
+               mono_array_setref (this->cached_culture_info, free_slot, culture);
+       /* we may want to replace an existing entry here, even when no suitable slot is found */
        mono_monitor_exit (this->synch_lock);
 }
 
+void
+ves_icall_System_Threading_Thread_SetCachedCurrentCulture (MonoThread *this, MonoObject *culture)
+{
+       cache_culture (this, culture, CULTURES_START_IDX);
+}
+
 void
 ves_icall_System_Threading_Thread_SetSerializedCurrentCulture (MonoThread *this, MonoArray *arr)
 {
@@ -726,21 +768,7 @@ ves_icall_System_Threading_Thread_SetSerializedCurrentCulture (MonoThread *this,
 MonoObject*
 ves_icall_System_Threading_Thread_GetCachedCurrentUICulture (MonoThread *this)
 {
-       MonoObject *res;
-       MonoDomain *domain;
-       int i;
-
-       /* No need to lock here */
-       if (this->ui_culture_info) {
-               domain = mono_domain_get ();
-               for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
-                       res = this->ui_culture_info [i];
-                       if (res && res->vtable->domain == domain)
-                               return res;
-               }
-       }
-
-       return NULL;
+       return lookup_cached_culture (this, mono_domain_get (), UICULTURES_START_IDX);
 }
 
 MonoArray*
@@ -752,9 +780,9 @@ ves_icall_System_Threading_Thread_GetSerializedCurrentUICulture (MonoThread *thi
        if (this->serialized_ui_culture_info) {
                res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_ui_culture_info_len);
                memcpy (mono_array_addr (res, guint8, 0), this->serialized_ui_culture_info, this->serialized_ui_culture_info_len);
-       }
-       else
+       } else {
                res = NULL;
+       }
        mono_monitor_exit (this->synch_lock);
 
        return res;
@@ -763,27 +791,7 @@ ves_icall_System_Threading_Thread_GetSerializedCurrentUICulture (MonoThread *thi
 void
 ves_icall_System_Threading_Thread_SetCachedCurrentUICulture (MonoThread *this, MonoObject *culture)
 {
-       int i;
-       MonoDomain *domain = mono_domain_get ();
-
-       mono_monitor_enter (this->synch_lock);
-       if (!this->ui_culture_info) {
-               this->ui_culture_info = mono_gc_alloc_fixed (sizeof (MonoObject*) * NUM_CACHED_CULTURES, NULL);
-       }
-
-       for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
-               if (this->ui_culture_info [i]) {
-                       if (this->ui_culture_info [i]->vtable->domain == domain)
-                               /* Replace */
-                               break;
-               }
-               else
-                       /* Free entry */
-                       break;
-       }
-       if (i < NUM_CACHED_CULTURES)
-               this->ui_culture_info [i] = culture;
-       mono_monitor_exit (this->synch_lock);
+       cache_culture (this, culture, UICULTURES_START_IDX);
 }
 
 void
@@ -802,7 +810,7 @@ ves_icall_System_Threading_Thread_SetSerializedCurrentUICulture (MonoThread *thi
 MonoThread *
 mono_thread_current (void)
 {
-       THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": returning %p", GET_CURRENT_OBJECT ()));
+       THREAD_DEBUG (g_message ("%s: returning %p", __func__, GET_CURRENT_OBJECT ()));
        return GET_CURRENT_OBJECT ();
 }
 
@@ -821,14 +829,15 @@ 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);
 
        if(ms== -1) {
                ms=INFINITE;
        }
-       THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": joining thread handle %p, %d ms",
-                  thread, ms));
+       THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__, thread, ms));
        
        ret=WaitForSingleObjectEx (thread, ms, TRUE);
 
@@ -837,12 +846,12 @@ gboolean ves_icall_System_Threading_Thread_Join_internal(MonoThread *this,
        mono_monitor_exit (this->synch_lock);
        
        if(ret==WAIT_OBJECT_0) {
-               THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": join successful"));
+               THREAD_DEBUG (g_message ("%s: join successful", __func__));
 
                return(TRUE);
        }
        
-       THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": join failed"));
+       THREAD_DEBUG (g_message ("%s: join failed", __func__));
 
        return(FALSE);
 }
@@ -860,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);
 
@@ -891,7 +903,7 @@ gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_
        g_free(handles);
 
        if(ret==WAIT_FAILED) {
-               THREAD_WAIT_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%"G_GSIZE_FORMAT") Wait failed", GetCurrentThreadId ()));
+               THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
                return(FALSE);
        } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
                /* Do we want to try again if we get
@@ -899,7 +911,7 @@ gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_
                 * WaitHandle doesn't give any clues.  (We'd have to
                 * fiddle with the timeout if we retry.)
                 */
-               THREAD_WAIT_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%"G_GSIZE_FORMAT") Wait timed out", GetCurrentThreadId ()));
+               THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
                return(FALSE);
        }
        
@@ -919,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);
 
@@ -949,7 +964,7 @@ gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_ha
 
        g_free(handles);
 
-       THREAD_WAIT_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%"G_GSIZE_FORMAT") returning %d", GetCurrentThreadId (), ret));
+       THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") returning %d", __func__, GetCurrentThreadId (), ret));
 
        /*
         * These need to be here.  See MSDN dos on WaitForMultipleObjects.
@@ -973,12 +988,14 @@ gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this
        
        MONO_ARCH_SAVE_REGS;
 
-       THREAD_WAIT_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%"G_GSIZE_FORMAT") waiting for %p, %d ms", GetCurrentThreadId (), handle, ms));
+       THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for %p, %d ms", __func__, GetCurrentThreadId (), handle, ms));
        
        if(ms== -1) {
                ms=INFINITE;
        }
        
+       mono_thread_current_check_pending_interrupt ();
+
        mono_monitor_enter (thread->synch_lock);
        thread->state |= ThreadState_WaitSleepJoin;
        mono_monitor_exit (thread->synch_lock);
@@ -990,7 +1007,7 @@ gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this
        mono_monitor_exit (thread->synch_lock);
 
        if(ret==WAIT_FAILED) {
-               THREAD_WAIT_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%"G_GSIZE_FORMAT") Wait failed", GetCurrentThreadId ()));
+               THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
                return(FALSE);
        } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
                /* Do we want to try again if we get
@@ -998,7 +1015,7 @@ gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this
                 * WaitHandle doesn't give any clues.  (We'd have to
                 * fiddle with the timeout if we retry.)
                 */
-               THREAD_WAIT_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%"G_GSIZE_FORMAT") Wait timed out", GetCurrentThreadId ()));
+               THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
                return(FALSE);
        }
        
@@ -1032,11 +1049,94 @@ void ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
        ReleaseMutex(handle);
 }
 
-HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name) {
+HANDLE ves_icall_System_Threading_Mutex_OpenMutex_internal (MonoString *name,
+                                                           gint32 rights,
+                                                           gint32 *error)
+{
+       HANDLE ret;
+       
+       MONO_ARCH_SAVE_REGS;
+       
+       *error = ERROR_SUCCESS;
+       
+       ret = OpenMutex (rights, FALSE, mono_string_chars (name));
+       if (ret == NULL) {
+               *error = GetLastError ();
+       }
+       
+       return(ret);
+}
+
+
+HANDLE ves_icall_System_Threading_Semaphore_CreateSemaphore_internal (gint32 initialCount, gint32 maximumCount, MonoString *name, MonoBoolean *created)
+{ 
+       HANDLE sem;
+       
+       MONO_ARCH_SAVE_REGS;
+   
+       *created = TRUE;
+       
+       if (name == NULL) {
+               sem = CreateSemaphore (NULL, initialCount, maximumCount, NULL);
+       } else {
+               sem = CreateSemaphore (NULL, initialCount, maximumCount,
+                                      mono_string_chars (name));
+               
+               if (GetLastError () == ERROR_ALREADY_EXISTS) {
+                       *created = FALSE;
+               }
+       }
+
+       return(sem);
+}                                                                   
+
+gint32 ves_icall_System_Threading_Semaphore_ReleaseSemaphore_internal (HANDLE handle, gint32 releaseCount, MonoBoolean *fail)
+{ 
+       gint32 prevcount;
+       
+       MONO_ARCH_SAVE_REGS;
+
+       *fail = !ReleaseSemaphore (handle, releaseCount, &prevcount);
+
+       return (prevcount);
+}
+
+HANDLE ves_icall_System_Threading_Semaphore_OpenSemaphore_internal (MonoString *name, gint32 rights, gint32 *error)
+{
+       HANDLE ret;
+       
+       MONO_ARCH_SAVE_REGS;
+       
+       *error = ERROR_SUCCESS;
+       
+       ret = OpenSemaphore (rights, FALSE, mono_string_chars (name));
+       if (ret == NULL) {
+               *error = GetLastError ();
+       }
+       
+       return(ret);
+}
+
+HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name, MonoBoolean *created)
+{
+       HANDLE event;
+       
        MONO_ARCH_SAVE_REGS;
 
-       return(CreateEvent (NULL, manual, initial,
-                           name==NULL?NULL:mono_string_chars (name)));
+       *created = TRUE;
+
+       if (name == NULL) {
+               event = CreateEvent (NULL, manual, initial, NULL);
+       } else {
+               event = CreateEvent (NULL, manual, initial,
+                                    mono_string_chars (name));
+               
+               if (GetLastError () == ERROR_ALREADY_EXISTS) {
+                       *created = FALSE;
+               }
+       }
+       
+       return(event);
 }
 
 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
@@ -1058,6 +1158,24 @@ ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
        CloseHandle (handle);
 }
 
+HANDLE ves_icall_System_Threading_Events_OpenEvent_internal (MonoString *name,
+                                                            gint32 rights,
+                                                            gint32 *error)
+{
+       HANDLE ret;
+       
+       MONO_ARCH_SAVE_REGS;
+       
+       *error = ERROR_SUCCESS;
+       
+       ret = OpenEvent (rights, FALSE, mono_string_chars (name));
+       if (ret == NULL) {
+               *error = GetLastError ();
+       }
+       
+       return(ret);
+}
+
 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
 {
        MONO_ARCH_SAVE_REGS;
@@ -1071,11 +1189,11 @@ gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
 
        MONO_ARCH_SAVE_REGS;
 
-       EnterCriticalSection(&interlocked_mutex);
+       mono_interlocked_lock ();
 
        ret = ++ *location;
        
-       LeaveCriticalSection(&interlocked_mutex);
+       mono_interlocked_unlock ();
 
        
        return ret;
@@ -1094,11 +1212,11 @@ gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
 
        MONO_ARCH_SAVE_REGS;
 
-       EnterCriticalSection(&interlocked_mutex);
+       mono_interlocked_lock ();
 
        ret = -- *location;
        
-       LeaveCriticalSection(&interlocked_mutex);
+       mono_interlocked_unlock ();
 
        return ret;
 }
@@ -1141,10 +1259,10 @@ ves_icall_System_Threading_Interlocked_Exchange_Long (gint64 *location, gint64 v
         * According to MSDN, this function is only atomic with regards to the 
         * other Interlocked functions on 32 bit platforms.
         */
-       EnterCriticalSection(&interlocked_mutex);
+       mono_interlocked_lock ();
        res = *location;
        *location = value;
-       LeaveCriticalSection(&interlocked_mutex);
+       mono_interlocked_unlock ();
 
        return res;
 #endif
@@ -1167,10 +1285,10 @@ ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble *location, gdoub
         * According to MSDN, this function is only atomic with regards to the 
         * other Interlocked functions on 32 bit platforms.
         */
-       EnterCriticalSection(&interlocked_mutex);
+       mono_interlocked_lock ();
        res = *location;
        *location = value;
-       LeaveCriticalSection(&interlocked_mutex);
+       mono_interlocked_unlock ();
 
        return res;
 #endif
@@ -1217,11 +1335,11 @@ ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble *location
 #else
        gdouble old;
 
-       EnterCriticalSection(&interlocked_mutex);
+       mono_interlocked_lock ();
        old = *location;
        if (old == comparand)
                *location = value;
-       LeaveCriticalSection(&interlocked_mutex);
+       mono_interlocked_unlock ();
 
        return old;
 #endif
@@ -1235,16 +1353,32 @@ ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64 *location, g
 #else
        gint64 old;
 
-       EnterCriticalSection(&interlocked_mutex);
+       mono_interlocked_lock ();
        old = *location;
        if (old == comparand)
                *location = value;
-       LeaveCriticalSection(&interlocked_mutex);
+       mono_interlocked_unlock ();
        
        return old;
 #endif
 }
 
+MonoObject*
+ves_icall_System_Threading_Interlocked_CompareExchange_T (MonoObject **location, MonoObject *value, MonoObject *comparand)
+{
+       MONO_ARCH_SAVE_REGS;
+
+       return InterlockedCompareExchangePointer ((gpointer *)location, value, comparand);
+}
+
+MonoObject*
+ves_icall_System_Threading_Interlocked_Exchange_T (MonoObject **location, MonoObject *value)
+{
+       MONO_ARCH_SAVE_REGS;
+
+       return InterlockedExchangePointer ((gpointer *)location, value);
+}
+
 gint32 
 ves_icall_System_Threading_Interlocked_Add_Int (gint32 *location, gint32 value)
 {
@@ -1255,12 +1389,12 @@ ves_icall_System_Threading_Interlocked_Add_Int (gint32 *location, gint32 value)
 #else
        gint32 orig;
 
-       EnterCriticalSection(&interlocked_mutex);
+       mono_interlocked_lock ();
        orig = *location;
        *location = orig + value;
-       LeaveCriticalSection(&interlocked_mutex);
+       mono_interlocked_unlock ();
 
-       return orig;
+       return orig + value;
 #endif
 }
 
@@ -1274,12 +1408,12 @@ ves_icall_System_Threading_Interlocked_Add_Long (gint64 *location, gint64 value)
 #else
        gint64 orig;
 
-       EnterCriticalSection(&interlocked_mutex);
+       mono_interlocked_lock ();
        orig = *location;
        *location = orig + value;
-       LeaveCriticalSection(&interlocked_mutex);
+       mono_interlocked_unlock ();
 
-       return orig;
+       return orig + value;
 #endif
 }
 
@@ -1292,9 +1426,9 @@ ves_icall_System_Threading_Interlocked_Read_Long (gint64 *location)
 #else
        gint64 res;
 
-       EnterCriticalSection(&interlocked_mutex);
+       mono_interlocked_lock ();
        res = *location;
-       LeaveCriticalSection(&interlocked_mutex);
+       mono_interlocked_unlock ();
 
        return res;
 #endif
@@ -1347,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)
 {
@@ -1418,7 +1593,8 @@ ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
        mono_monitor_enter (thread->synch_lock);
 
        if ((thread->state & ThreadState_AbortRequested) != 0 || 
-               (thread->state & ThreadState_StopRequested) != 0) 
+               (thread->state & ThreadState_StopRequested) != 0 ||
+               (thread->state & ThreadState_Stopped) != 0)
        {
                mono_monitor_exit (thread->synch_lock);
                return;
@@ -1431,12 +1607,12 @@ ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
        }
 
        thread->state |= ThreadState_AbortRequested;
-       thread->abort_state = state;
+       MONO_OBJECT_SETREF (thread, abort_state, state);
        thread->abort_exc = NULL;
 
        mono_monitor_exit (thread->synch_lock);
 
-       THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%"G_GSIZE_FORMAT") Abort requested for %p (%"G_GSIZE_FORMAT")", GetCurrentThreadId (), thread, (gsize)thread->tid));
+       THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Abort requested for %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
        
        /* Make sure the thread is awake */
        mono_thread_resume (thread);
@@ -1527,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);
@@ -1661,13 +1841,13 @@ 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);
 
        current_object_key=TlsAlloc();
-       THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Allocated current_object_key %d",
-                  current_object_key));
+       THREAD_DEBUG (g_message ("%s: Allocated current_object_key %d", __func__, current_object_key));
 
        mono_thread_start_cb = start_cb;
        mono_thread_attach_cb = attach_cb;
@@ -1680,15 +1860,40 @@ void mono_thread_init (MonoThreadStartCB start_cb,
        GetCurrentProcess ();
 }
 
-void
-mono_threads_install_cleanup (MonoThreadCleanupFunc func)
+void mono_thread_cleanup (void)
 {
-       mono_thread_cleanup = func;
+#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_install_thread_callbacks (MonoThreadCallbacks *callbacks)
+void
+mono_threads_install_cleanup (MonoThreadCleanupFunc func)
 {
-       mono_thread_callbacks = callbacks;
+       mono_thread_cleanup_fn = func;
 }
 
 G_GNUC_UNUSED
@@ -1714,14 +1919,13 @@ static void wait_for_tids (struct wait_data *wait, guint32 timeout)
 {
        guint32 i, ret;
        
-       THREAD_DEBUG (g_message(G_GNUC_PRETTY_FUNCTION
-                 ": %d threads to wait for in this batch", wait->num));
+       THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
 
        ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
 
        if(ret==WAIT_FAILED) {
                /* See the comment in build_wait_tids() */
-               THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Wait failed"));
+               THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
                return;
        }
        
@@ -1746,7 +1950,7 @@ static void wait_for_tids (struct wait_data *wait, guint32 timeout)
                         * same thread.)
                         */
        
-                       THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": cleaning up after thread %"G_GSIZE_FORMAT, tid));
+                       THREAD_DEBUG (g_message ("%s: cleaning up after thread %"G_GSIZE_FORMAT, __func__, tid));
                        thread_cleanup (wait->threads[i]);
                }
        }
@@ -1756,8 +1960,7 @@ static void wait_for_tids_or_state_change (struct wait_data *wait, guint32 timeo
 {
        guint32 i, ret, count;
        
-       THREAD_DEBUG (g_message(G_GNUC_PRETTY_FUNCTION
-                 ": %d threads to wait for in this batch", wait->num));
+       THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
 
        /* Add the thread state change event, so it wakes up if a thread changes
         * to background mode.
@@ -1772,7 +1975,7 @@ static void wait_for_tids_or_state_change (struct wait_data *wait, guint32 timeo
 
        if(ret==WAIT_FAILED) {
                /* See the comment in build_wait_tids() */
-               THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Wait failed"));
+               THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
                return;
        }
        
@@ -1784,16 +1987,14 @@ static void wait_for_tids_or_state_change (struct wait_data *wait, guint32 timeo
        
        if (ret < wait->num) {
                gsize tid = wait->threads[ret]->tid;
-               EnterCriticalSection (&threads_mutex);
+               mono_threads_lock ();
                if (mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
                        /* See comment in wait_for_tids about thread cleanup */
-                       LeaveCriticalSection (&threads_mutex);
-                       THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
-                                  ": cleaning up after thread %"G_GSIZE_FORMAT, tid));
+                       mono_threads_unlock ();
+                       THREAD_DEBUG (g_message ("%s: cleaning up after thread %"G_GSIZE_FORMAT, __func__, tid));
                        thread_cleanup (wait->threads [ret]);
-               }
-               else
-                       LeaveCriticalSection (&threads_mutex);
+               } else
+                       mono_threads_unlock ();
        }
 }
 
@@ -1808,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
@@ -1844,6 +2056,9 @@ remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
        MonoThread *thread = (MonoThread *) value;
        HANDLE handle;
 
+       if (wait->num >= MAXIMUM_WAIT_OBJECTS)
+               return FALSE;
+
        /* The finalizer thread is not a background thread */
        if (thread->tid != self && (thread->state & ThreadState_Background) != 0) {
        
@@ -1853,15 +2068,16 @@ remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
                
                if(thread->state & ThreadState_AbortRequested ||
                   thread->state & ThreadState_Aborted) {
-                       THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Thread id %"G_GSIZE_FORMAT" already aborting", (gsize)thread->tid));
+                       THREAD_DEBUG (g_message ("%s: Thread id %"G_GSIZE_FORMAT" already aborting", __func__, (gsize)thread->tid));
                        return(TRUE);
                }
 
+               /* printf ("A: %d\n", wait->num); */
                wait->handles[wait->num]=thread->handle;
                wait->threads[wait->num]=thread;
                wait->num++;
 
-               THREAD_DEBUG (g_print (G_GNUC_PRETTY_FUNCTION ": Aborting id: %"G_GSIZE_FORMAT"\n", (gsize)thread->tid));
+               THREAD_DEBUG (g_print ("%s: Aborting id: %"G_GSIZE_FORMAT"\n", __func__, (gsize)thread->tid));
                mono_thread_stop (thread);
                return TRUE;
        }
@@ -1874,54 +2090,56 @@ void mono_thread_manage (void)
        struct wait_data *wait=g_new0 (struct wait_data, 1);
        
        /* join each thread that's still running */
-       THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Joining each running thread..."));
+       THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__));
        
-       EnterCriticalSection (&threads_mutex);
+       mono_threads_lock ();
        if(threads==NULL) {
-               THREAD_DEBUG (g_message(G_GNUC_PRETTY_FUNCTION ": No threads"));
-               LeaveCriticalSection (&threads_mutex);
+               THREAD_DEBUG (g_message("%s: No threads", __func__));
+               mono_threads_unlock ();
                return;
        }
-       LeaveCriticalSection (&threads_mutex);
+       mono_threads_unlock ();
        
        do {
-               EnterCriticalSection (&threads_mutex);
-               THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
-                         ":There are %d threads to join", mono_g_hash_table_size (threads));
+               mono_threads_lock ();
+               THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__, mono_g_hash_table_size (threads));
                        mono_g_hash_table_foreach (threads, print_tids, NULL));
        
                ResetEvent (background_change_event);
                wait->num=0;
                mono_g_hash_table_foreach (threads, build_wait_tids, wait);
-               LeaveCriticalSection (&threads_mutex);
+               mono_threads_unlock ();
                if(wait->num>0) {
                        /* Something to wait for */
                        wait_for_tids_or_state_change (wait, INFINITE);
                }
-               THREAD_DEBUG (g_message ("I have %d threads after waiting.", wait->num));
+               THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__, wait->num));
        } while(wait->num>0);
 
        mono_runtime_set_shutting_down ();
 
-       THREAD_DEBUG (g_message ("threadpool cleanup"));
+       THREAD_DEBUG (g_message ("%s: threadpool cleanup", __func__));
        mono_thread_pool_cleanup ();
 
-       EnterCriticalSection(&threads_mutex);
-
        /* 
         * Remove everything but the finalizer thread and self.
         * Also abort all the background threads
         * */
-       wait->num = 0;
-       mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
+       do {
+               mono_threads_lock ();
 
-       LeaveCriticalSection(&threads_mutex);
+               wait->num = 0;
+               mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
 
-       THREAD_DEBUG (g_message ("wait->num is now %d", wait->num));
-       if(wait->num>0) {
-               /* Something to wait for */
-               wait_for_tids (wait, INFINITE);
-       }
+               mono_threads_unlock ();
+
+               THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__, wait->num));
+               if(wait->num>0) {
+                       /* Something to wait for */
+                       wait_for_tids (wait, INFINITE);
+               }
+       } while (wait->num > 0);
+       
        /* 
         * give the subthreads a chance to really quit (this is mainly needed
         * to get correct user and system times from getrusage/wait/time(1)).
@@ -1947,14 +2165,14 @@ void mono_thread_abort_all_other_threads (void)
 {
        gsize self = GetCurrentThreadId ();
 
-       EnterCriticalSection (&threads_mutex);
-       THREAD_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ":There are %d threads to abort",
-                 mono_g_hash_table_size (threads));
-               mono_g_hash_table_foreach (threads, print_tids, NULL));
+       mono_threads_lock ();
+       THREAD_DEBUG (g_message ("%s: There are %d threads to abort", __func__,
+                                mono_g_hash_table_size (threads));
+                     mono_g_hash_table_foreach (threads, print_tids, NULL));
 
        mono_g_hash_table_foreach (threads, terminate_thread, (gpointer)self);
        
-       LeaveCriticalSection (&threads_mutex);
+       mono_threads_unlock ();
 }
 
 static void
@@ -1992,9 +2210,9 @@ void mono_thread_suspend_all_other_threads (void)
         * Make a copy of the hashtable since we can't do anything with
         * threads while threads_mutex is held.
         */
-       EnterCriticalSection (&threads_mutex);
+       mono_threads_lock ();
        mono_g_hash_table_foreach (threads, collect_threads, wait);
-       LeaveCriticalSection (&threads_mutex);
+       mono_threads_unlock ();
 
        events = g_new0 (gpointer, wait->num);
        waitnum = 0;
@@ -2026,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);
@@ -2053,6 +2277,38 @@ void mono_thread_suspend_all_other_threads (void)
        g_free (wait);
 }
 
+/**
+ * mono_threads_request_thread_dump:
+ *
+ *   Ask all threads except the current to print their stacktrace to stdout.
+ */
+void
+mono_threads_request_thread_dump (void)
+{
+       struct wait_data *wait = g_new0 (struct wait_data, 1);
+       int i;
+
+       /* 
+        * Make a copy of the hashtable since we can't do anything with
+        * threads while threads_mutex is held.
+        */
+       mono_threads_lock ();
+       mono_g_hash_table_foreach (threads, collect_threads, wait);
+       mono_threads_unlock ();
+
+       for (i = 0; i < wait->num; ++i) {
+               MonoThread *thread = wait->threads [i];
+
+               if (!mono_gc_is_finalizer_thread (thread) && (thread != mono_thread_current ()) && !thread->thread_dump_requested) {
+                       thread->thread_dump_requested = TRUE;
+
+                       signal_thread_state_change (thread);
+               }
+
+               CloseHandle (wait->handles [i]);
+       }
+}
+
 /*
  * mono_thread_push_appdomain_ref:
  *
@@ -2067,9 +2323,9 @@ mono_thread_push_appdomain_ref (MonoDomain *domain)
 
        if (thread) {
                /* printf ("PUSH REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
-               EnterCriticalSection (&threads_mutex);
+               mono_threads_lock ();
                thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
-               LeaveCriticalSection (&threads_mutex);
+               mono_threads_unlock ();
        }
 }
 
@@ -2080,11 +2336,11 @@ mono_thread_pop_appdomain_ref (void)
 
        if (thread) {
                /* printf ("POP REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
-               EnterCriticalSection (&threads_mutex);
+               mono_threads_lock ();
                /* FIXME: How can the list be empty ? */
                if (thread->appdomain_refs)
                        thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
-               LeaveCriticalSection (&threads_mutex);
+               mono_threads_unlock ();
        }
 }
 
@@ -2092,9 +2348,9 @@ gboolean
 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
 {
        gboolean res;
-       EnterCriticalSection (&threads_mutex);
+       mono_threads_lock ();
        res = g_slist_find (thread->appdomain_refs, domain) != NULL;
-       LeaveCriticalSection (&threads_mutex);
+       mono_threads_unlock ();
        return res;
 }
 
@@ -2146,12 +2402,12 @@ mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
 
        start_time = GetTickCount ();
        do {
-               EnterCriticalSection (&threads_mutex);
+               mono_threads_lock ();
 
                user_data.domain = domain;
                user_data.wait.num = 0;
                mono_g_hash_table_foreach (threads, abort_appdomain_thread, &user_data);
-               LeaveCriticalSection (&threads_mutex);
+               mono_threads_unlock ();
 
                if (user_data.wait.num > 0)
                        /*
@@ -2182,17 +2438,13 @@ clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
        int i;
 
        /* No locking needed here */
+       /* FIXME: why no locking? writes to the cache are protected with synch_lock above */
 
-       if (thread->culture_info) {
-               for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
-                       if (thread->culture_info [i] && thread->culture_info [i]->vtable->domain == domain)
-                               thread->culture_info [i] = NULL;
-               }
-       }
-       if (thread->ui_culture_info) {
-               for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
-                       if (thread->ui_culture_info [i] && thread->ui_culture_info [i]->vtable->domain == domain)
-                               thread->ui_culture_info [i] = NULL;
+       if (thread->cached_culture_info) {
+               for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i) {
+                       MonoObject *obj = mono_array_get (thread->cached_culture_info, MonoObject*, i);
+                       if (obj && obj->vtable->domain == domain)
+                               mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
                }
        }
 }
@@ -2206,9 +2458,9 @@ clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
 void
 mono_threads_clear_cached_culture (MonoDomain *domain)
 {
-       EnterCriticalSection (&threads_mutex);
+       mono_threads_lock ();
        mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
-       LeaveCriticalSection (&threads_mutex);
+       mono_threads_unlock ();
 }
 
 /*
@@ -2328,13 +2580,13 @@ thread_adjust_static_data (MonoThread *thread)
 {
        guint32 offset;
 
-       EnterCriticalSection (&threads_mutex);
+       mono_threads_lock ();
        if (thread_static_info.offset || thread_static_info.idx > 0) {
                /* get the current allocated size */
                offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
                mono_alloc_static_data (&(thread->static_data), offset);
        }
-       LeaveCriticalSection (&threads_mutex);
+       mono_threads_unlock ();
 }
 
 static void 
@@ -2360,19 +2612,19 @@ mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align
        guint32 offset;
        if (static_type == SPECIAL_STATIC_THREAD)
        {
-               EnterCriticalSection (&threads_mutex);
+               mono_threads_lock ();
                offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
                /* This can be called during startup */
                if (threads != NULL)
                        mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
-               LeaveCriticalSection (&threads_mutex);
+               mono_threads_unlock ();
        }
        else
        {
                g_assert (static_type == SPECIAL_STATIC_CONTEXT);
-               EnterCriticalSection (&contexts_mutex);
+               mono_contexts_lock ();
                offset = mono_alloc_static_data_slot (&context_static_info, size, align);
-               LeaveCriticalSection (&contexts_mutex);
+               mono_contexts_unlock ();
                offset |= 0x80000000;   /* Set the high bit to indicate context static data */
        }
        return offset;
@@ -2401,64 +2653,76 @@ mono_get_special_static_data (guint32 offset)
                */
                MonoAppContext *context = mono_context_get ();
                if (!context->static_data || !context->static_data [idx]) {
-                       EnterCriticalSection (&contexts_mutex);
+                       mono_contexts_lock ();
                        mono_alloc_static_data (&(context->static_data), offset);
-                       LeaveCriticalSection (&contexts_mutex);
+                       mono_contexts_unlock ();
                }
                return ((char*) context->static_data [idx]) + (offset & 0xffffff);      
        }
 }
 
-static void gc_stop_world (gpointer key, gpointer value, gpointer user)
-{
-       MonoThread *thread=(MonoThread *)value;
-
-       LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %"G_GSIZE_FORMAT" - %"G_GSIZE_FORMAT, (gsize)user, (gsize)thread->tid));
-
-       if(thread->tid == (gsize)user)
-               return;
-
-       SuspendThread (thread->handle);
-}
+static MonoClassField *local_slots = NULL;
 
-void mono_gc_stop_world (void)
-{
-       gsize self = GetCurrentThreadId ();
-
-       LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %"G_GSIZE_FORMAT" - %p", self, threads));
-
-       EnterCriticalSection (&threads_mutex);
-
-       if (threads != NULL)
-               mono_g_hash_table_foreach (threads, gc_stop_world, (gpointer)self);
-       
-       LeaveCriticalSection (&threads_mutex);
-}
+typedef struct {
+       /* local tls data to get locals_slot from a thread */
+       guint32 offset;
+       int idx;
+       /* index in the locals_slot array */
+       int slot;
+} LocalSlotID;
 
-static void gc_start_world (gpointer key, gpointer value, gpointer user)
+static void
+clear_local_slot (gpointer key, gpointer value, gpointer user_data)
 {
-       MonoThread *thread=(MonoThread *)value;
-       
-       LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %"G_GSIZE_FORMAT" - %"G_GSIZE_FORMAT, (gsize)user, (gsize)thread->tid));
-
-       if(thread->tid == (gsize)user)
+       LocalSlotID *sid = user_data;
+       MonoThread *thread = (MonoThread*)value;
+       MonoArray *slots_array;
+       /*
+        * the static field is stored at: ((char*) thread->static_data [idx]) + (offset & 0xffffff);
+        * it is for the right domain, so we need to check if it is allocated an initialized
+        * for the current thread.
+        */
+       /*g_print ("handling thread %p\n", thread);*/
+       if (!thread->static_data || !thread->static_data [sid->idx])
                return;
-
-       ResumeThread (thread->handle);
+       slots_array = *(MonoArray **)(((char*) thread->static_data [sid->idx]) + (sid->offset & 0xffffff));
+       if (!slots_array || sid->slot >= mono_array_length (slots_array))
+               return;
+       mono_array_set (slots_array, MonoObject*, sid->slot, NULL);
 }
 
-void mono_gc_start_world (void)
+void
+mono_thread_free_local_slot_values (int slot, MonoBoolean thread_local)
 {
-       gsize self = GetCurrentThreadId ();
-
-       LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %"G_GSIZE_FORMAT" - %p", self, threads));
-
-       EnterCriticalSection (&threads_mutex);
-
-       if (threads != NULL)
-               mono_g_hash_table_foreach (threads, gc_start_world, (gpointer)self);
-       
-       LeaveCriticalSection (&threads_mutex);
+       MonoDomain *domain;
+       LocalSlotID sid;
+       sid.slot = slot;
+       if (thread_local) {
+               void *addr = NULL;
+               if (!local_slots) {
+                       local_slots = mono_class_get_field_from_name (mono_defaults.thread_class, "local_slots");
+                       if (!local_slots) {
+                               g_warning ("local_slots field not found in Thread class");
+                               return;
+                       }
+               }
+               domain = mono_domain_get ();
+               mono_domain_lock (domain);
+               if (domain->special_static_fields)
+                       addr = g_hash_table_lookup (domain->special_static_fields, local_slots);
+               mono_domain_unlock (domain);
+               if (!addr)
+                       return;
+               /*g_print ("freeing slot %d at %p\n", slot, addr);*/
+               sid.offset = GPOINTER_TO_UINT (addr);
+               sid.offset &= 0x7fffffff;
+               sid.idx = (sid.offset >> 24) - 1;
+               mono_threads_lock ();
+               mono_g_hash_table_foreach (threads, clear_local_slot, &sid);
+               mono_threads_unlock ();
+       } else {
+               /* FIXME: clear the slot for MonoAppContexts, too */
+       }
 }
 
 #ifdef __MINGW32__
@@ -2491,7 +2755,7 @@ static MonoException* mono_thread_execute_interruption (MonoThread *thread)
 
        if ((thread->state & ThreadState_AbortRequested) != 0) {
                if (thread->abort_exc == NULL)
-                       thread->abort_exc = mono_get_exception_thread_abort ();
+                       MONO_OBJECT_SETREF (thread, abort_exc, mono_get_exception_thread_abort ());
                mono_monitor_exit (thread->synch_lock);
                return thread->abort_exc;
        }
@@ -2499,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);
@@ -2522,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);
@@ -2626,41 +2897,3 @@ gint32* mono_thread_interruption_request_flag ()
 {
        return &thread_interruption_requested;
 }
-
-#ifdef WITH_INCLUDED_LIBGC
-
-static void gc_push_all_stacks (gpointer key, gpointer value, gpointer user)
-{
-       MonoThread *thread=(MonoThread *)value;
-       gsize *selfp = (gsize *)user, self = *selfp;
-
-       LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %"G_GSIZE_FORMAT" - %"G_GSIZE_FORMAT" - %p", self, (gsize)thread->tid, thread->stack_ptr));
-
-       if(thread->tid == self) {
-               LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %p - %p", selfp, thread->stack_ptr));
-               GC_push_all_stack (selfp, thread->stack_ptr);
-               return;
-       }
-
-#ifdef PLATFORM_WIN32
-       GC_win32_push_thread_stack (thread->handle, thread->stack_ptr);
-#else
-       mono_wapi_push_thread_stack (thread->handle, thread->stack_ptr);
-#endif
-}
-
-void mono_gc_push_all_stacks (void)
-{
-       gsize self = GetCurrentThreadId ();
-
-       LIBGC_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": %"G_GSIZE_FORMAT" - %p", self, threads));
-
-       EnterCriticalSection (&threads_mutex);
-
-       if (threads != NULL)
-               mono_g_hash_table_foreach (threads, gc_push_all_stacks, &self);
-       
-       LeaveCriticalSection (&threads_mutex);
-}
-
-#endif /* WITH_INCLUDED_LIBGC */