2 * threads.c: Thread support internal calls
5 * Dick Porter (dick@ximian.com)
6 * Paolo Molaro (lupus@ximian.com)
7 * Patrik Torstensson (patrik.torstensson@labs2.com)
9 * (C) 2001 Ximian, Inc.
14 #define _WIN32_WINNT 0x0500
21 #include <mono/metadata/object.h>
22 #include <mono/metadata/domain-internals.h>
23 #include <mono/metadata/profiler-private.h>
24 #include <mono/metadata/threads.h>
25 #include <mono/metadata/threadpool.h>
26 #include <mono/metadata/threads-types.h>
27 #include <mono/metadata/exception.h>
28 #include <mono/metadata/environment.h>
29 #include <mono/metadata/monitor.h>
30 #include <mono/metadata/gc-internal.h>
31 #include <mono/metadata/marshal.h>
32 #include <mono/io-layer/io-layer.h>
34 #include <mono/os/gc_wrapper.h>
37 #undef THREAD_WAIT_DEBUG
41 guint32 (*func)(void *);
58 * The "os_handle" field of the WaitHandle class.
60 static MonoClassField *wait_handle_os_handle_field = NULL;
62 /* Controls access to the 'threads' hash table */
63 static CRITICAL_SECTION threads_mutex;
65 /* Controls access to context static data */
66 static CRITICAL_SECTION contexts_mutex;
68 /* Holds current status of static data heap */
69 static StaticDataInfo thread_static_info;
70 static StaticDataInfo context_static_info;
72 /* The hash of existing threads (key is thread ID) that need joining
75 static MonoGHashTable *threads=NULL;
77 /* The TLS key that holds the MonoObject assigned to each thread */
78 static guint32 current_object_key = -1;
81 /* we need to use both the Tls* functions and __thread because
82 * the gc needs to see all the threads
84 static __thread MonoThread * tls_current_object;
85 #define SET_CURRENT_OBJECT(x) do { \
86 tls_current_object = x; \
87 TlsSetValue (current_object_key, thread); \
89 #define GET_CURRENT_OBJECT() tls_current_object
91 #define SET_CURRENT_OBJECT(x) TlsSetValue (current_object_key, thread);
92 #define GET_CURRENT_OBJECT() (MonoThread*) TlsGetValue (current_object_key);
95 /* function called at thread start */
96 static MonoThreadStartCB mono_thread_start_cb = NULL;
98 /* function called at thread attach */
99 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
101 /* function called at thread cleanup */
102 static MonoThreadCleanupFunc mono_thread_cleanup = NULL;
104 /* function called when a new thread has been created */
105 static MonoThreadCallbacks *mono_thread_callbacks = NULL;
107 /* The TLS key that holds the LocalDataStoreSlot hash in each thread */
108 static guint32 slothash_key = -1;
110 /* The default stack size for each thread */
111 static guint32 default_stacksize = 0;
113 static void thread_adjust_static_data (MonoThread *thread);
114 static void mono_init_static_data_info (StaticDataInfo *static_data);
115 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
117 /* Spin lock for InterlockedXXX 64 bit functions */
118 static CRITICAL_SECTION interlocked_mutex;
120 /* Controls access to interruption flag */
121 static CRITICAL_SECTION interruption_mutex;
123 /* global count of thread interruptions requested */
124 static gint32 thread_interruption_requested = 0;
127 /* handle_store() and handle_remove() manage the array of threads that
128 * still need to be waited for when the main thread exits.
130 static void handle_store(MonoThread *thread)
132 EnterCriticalSection(&threads_mutex);
135 g_message(G_GNUC_PRETTY_FUNCTION ": thread %p ID %d", thread,
140 MONO_GC_REGISTER_ROOT (threads);
141 threads=mono_g_hash_table_new(NULL, NULL);
144 /* We don't need to duplicate thread->handle, because it is
145 * only closed when the thread object is finalized by the GC.
147 mono_g_hash_table_insert(threads, GUINT_TO_POINTER(thread->tid), thread);
148 LeaveCriticalSection(&threads_mutex);
151 static void handle_remove(guint32 tid)
154 g_message(G_GNUC_PRETTY_FUNCTION ": thread ID %d", tid);
157 EnterCriticalSection(&threads_mutex);
160 mono_g_hash_table_remove (threads, GUINT_TO_POINTER(tid));
162 LeaveCriticalSection(&threads_mutex);
164 /* Don't close the handle here, wait for the object finalizer
165 * to do it. Otherwise, the following race condition applies:
167 * 1) Thread exits (and handle_remove() closes the handle)
169 * 2) Some other handle is reassigned the same slot
171 * 3) Another thread tries to join the first thread, and
172 * blocks waiting for the reassigned handle to be signalled
173 * (which might never happen). This is possible, because the
174 * thread calling Join() still has a reference to the first
179 static void thread_cleanup (MonoThread *thread)
181 if (!mono_monitor_enter (thread->synch_lock))
184 thread->state |= ThreadState_Stopped;
185 mono_monitor_exit (thread->synch_lock);
187 mono_profiler_thread_end (thread->tid);
188 handle_remove (thread->tid);
190 mono_thread_pop_appdomain_ref ();
192 if (mono_thread_cleanup)
193 mono_thread_cleanup (thread);
196 static guint32 start_wrapper(void *data)
198 struct StartInfo *start_info=(struct StartInfo *)data;
199 guint32 (*start_func)(void *);
202 MonoThread *thread=start_info->obj;
205 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Start wrapper",
206 GetCurrentThreadId ());
209 /* We can be sure start_info->obj->tid and
210 * start_info->obj->handle have been set, because the thread
211 * was created suspended, and these values were set before the
217 SET_CURRENT_OBJECT (thread);
219 if (!mono_domain_set (start_info->domain, FALSE)) {
220 /* No point in raising an appdomain_unloaded exception here */
221 /* FIXME: Cleanup here */
225 start_func = start_info->func;
226 this = start_info->this;
228 /* This MUST be called before any managed code can be
229 * executed, as it calls the callback function that (for the
230 * jit) sets the lmf marker.
232 mono_thread_new_init (tid, &tid, start_func);
233 thread->stack_ptr = &tid;
236 g_message (G_GNUC_PRETTY_FUNCTION
237 ": (%d,%d) Setting thread stack to %p",
238 GetCurrentThreadId (), getpid (), thread->stack_ptr);
242 g_message (G_GNUC_PRETTY_FUNCTION
243 ": (%d) Setting current_object_key to %p",
244 GetCurrentThreadId (), thread);
247 mono_profiler_thread_start (tid);
249 if(thread->start_notify!=NULL) {
250 /* Let the thread that called Start() know we're
253 ReleaseSemaphore (thread->start_notify, 1, NULL);
258 /* Every thread references the appdomain which created it */
259 mono_thread_push_appdomain_ref (mono_domain_get ());
261 thread_adjust_static_data (thread);
262 #ifndef PLATFORM_WIN32
264 g_message (G_GNUC_PRETTY_FUNCTION "start_wrapper for %d\n", thread->tid);
266 pthread_cleanup_push ((void (*) (void *)) mono_thread_detach, thread);
270 #ifdef PLATFORM_WIN32
271 /* If the thread calls ExitThread at all, this remaining code
272 * will not be executed, but the main thread will eventually
273 * call thread_cleanup() on this thread's behalf.
277 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Start wrapper terminating",
278 GetCurrentThreadId ());
281 /* Remove the reference to the thread object in the TLS data,
282 * so the thread object can be finalized. This won't be
283 * reached if the thread threw an uncaught exception, so those
284 * thread handles will stay referenced :-( (This is due to
285 * missing support for scanning thread-specific data in the
286 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
289 SET_CURRENT_OBJECT (NULL);
291 thread_cleanup (thread);
293 pthread_cleanup_pop (1);
299 void mono_thread_new_init (guint32 tid, gpointer stack_start, gpointer func)
301 if (mono_thread_start_cb) {
302 mono_thread_start_cb (tid, stack_start, func);
305 if (mono_thread_callbacks)
306 (* mono_thread_callbacks->thread_created) (tid, stack_start, func);
309 void mono_threads_set_default_stacksize (guint32 stacksize)
311 default_stacksize = stacksize;
314 guint32 mono_threads_get_default_stacksize (void)
316 return default_stacksize;
319 void mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
322 HANDLE thread_handle;
323 struct StartInfo *start_info;
326 thread=(MonoThread *)mono_object_new (domain,
327 mono_defaults.thread_class);
329 start_info=g_new0 (struct StartInfo, 1);
330 start_info->func = func;
331 start_info->obj = thread;
332 start_info->domain = domain;
333 start_info->this = arg;
335 /* Create suspended, so we can do some housekeeping before the thread
338 #ifdef PLATFORM_WIN32
339 thread_handle = GC_CreateThread(NULL, default_stacksize, start_wrapper, start_info,
340 CREATE_SUSPENDED, &tid);
342 thread_handle = CreateThread(NULL, default_stacksize, start_wrapper, start_info,
343 CREATE_SUSPENDED, &tid);
346 g_message(G_GNUC_PRETTY_FUNCTION ": Started thread ID %d (handle %p)",
349 g_assert (thread_handle);
351 thread->handle=thread_handle;
354 thread->synch_lock=mono_object_new (domain, mono_defaults.object_class);
356 handle_store(thread);
358 ResumeThread (thread_handle);
362 mono_thread_attach (MonoDomain *domain)
365 HANDLE thread_handle;
368 if ((thread = mono_thread_current ())) {
369 /* Already attached */
373 thread = (MonoThread *)mono_object_new (domain,
374 mono_defaults.thread_class);
376 thread_handle = GetCurrentThread ();
377 g_assert (thread_handle);
379 tid=GetCurrentThreadId ();
381 thread->handle=thread_handle;
385 g_message(G_GNUC_PRETTY_FUNCTION ": Attached thread ID %d (handle %p)",
389 handle_store(thread);
392 g_message (G_GNUC_PRETTY_FUNCTION
393 ": (%d) Setting current_object_key to %p",
394 GetCurrentThreadId (), thread);
397 SET_CURRENT_OBJECT (thread);
398 mono_domain_set (domain, TRUE);
400 thread_adjust_static_data (thread);
402 if (mono_thread_attach_cb) {
403 mono_thread_attach_cb (tid, &tid);
410 mono_thread_detach (MonoThread *thread)
412 g_return_if_fail (thread != NULL);
415 g_message (G_GNUC_PRETTY_FUNCTION "mono_thread_detach for %d\n", thread->tid);
417 SET_CURRENT_OBJECT (NULL);
419 thread_cleanup (thread);
422 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
425 MonoMulticastDelegate *delegate = (MonoMulticastDelegate*)start;
426 guint32 (*start_func)(void *);
427 struct StartInfo *start_info;
435 g_message(G_GNUC_PRETTY_FUNCTION
436 ": Trying to start a new thread: this (%p) start (%p)",
440 im = mono_get_delegate_invoke (start->vtable->klass);
441 im = mono_marshal_get_delegate_invoke (im);
442 if (mono_thread_callbacks)
443 start_func = (* mono_thread_callbacks->thread_start_compile_func) (im);
445 start_func = mono_compile_method (im);
447 if(start_func==NULL) {
448 g_warning(G_GNUC_PRETTY_FUNCTION
449 ": Can't locate start method!");
452 /* This is freed in start_wrapper */
453 start_info = g_new0 (struct StartInfo, 1);
454 start_info->func = start_func;
455 start_info->this = delegate;
456 start_info->obj = this;
457 start_info->domain = mono_domain_get ();
459 this->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
460 if(this->start_notify==NULL) {
461 g_warning (G_GNUC_PRETTY_FUNCTION ": CreateSemaphore error 0x%x", GetLastError ());
465 thread=CreateThread(NULL, default_stacksize, start_wrapper, start_info,
466 CREATE_SUSPENDED, &tid);
468 g_warning(G_GNUC_PRETTY_FUNCTION
469 ": CreateThread error 0x%x", GetLastError());
476 /* Don't call handle_store() here, delay it to Start.
477 * We can't join a thread (trying to will just block
478 * forever) until it actually starts running, so don't
479 * store the handle till then.
483 g_message(G_GNUC_PRETTY_FUNCTION
484 ": Started thread ID %d (handle %p)", tid, thread);
491 void ves_icall_System_Threading_Thread_Thread_free_internal (MonoThread *this,
497 g_message (G_GNUC_PRETTY_FUNCTION ": Closing thread %p, handle %p",
501 CloseHandle (thread);
504 void ves_icall_System_Threading_Thread_Start_internal(MonoThread *this,
510 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Launching thread %p (%d)",
511 GetCurrentThreadId (), this, this->tid);
514 /* Only store the handle when the thread is about to be
515 * launched, to avoid the main thread deadlocking while trying
516 * to clean up a thread that will never be signalled.
520 if (mono_thread_callbacks)
521 (* mono_thread_callbacks->start_resume) (this->tid);
523 ResumeThread(thread);
525 if (mono_thread_callbacks)
526 (* mono_thread_callbacks->end_resume) (this->tid);
528 if(this->start_notify!=NULL) {
529 /* Wait for the thread to set up its TLS data etc, so
530 * theres no potential race condition if someone tries
531 * to look up the data believing the thread has
536 g_message(G_GNUC_PRETTY_FUNCTION
537 ": (%d) waiting for thread %p (%d) to start",
538 GetCurrentThreadId (), this, this->tid);
541 WaitForSingleObjectEx (this->start_notify, INFINITE, FALSE);
542 CloseHandle (this->start_notify);
543 this->start_notify=NULL;
547 g_message(G_GNUC_PRETTY_FUNCTION
548 ": (%d) Done launching thread %p (%d)",
549 GetCurrentThreadId (), this, this->tid);
553 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
555 MonoThread *thread = mono_thread_current ();
560 g_message(G_GNUC_PRETTY_FUNCTION ": Sleeping for %d ms", ms);
563 mono_monitor_enter (thread->synch_lock);
564 thread->state |= ThreadState_WaitSleepJoin;
565 mono_monitor_exit (thread->synch_lock);
569 mono_monitor_enter (thread->synch_lock);
570 thread->state &= ~ThreadState_WaitSleepJoin;
571 mono_monitor_exit (thread->synch_lock);
575 ves_icall_System_Threading_Thread_GetDomainID (void)
579 return mono_domain_get()->domain_id;
583 ves_icall_System_Threading_Thread_GetName_internal (MonoThread *this_obj)
588 return mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
592 ves_icall_System_Threading_Thread_SetName_internal (MonoThread *this_obj, MonoString *name)
595 g_free (this_obj->name);
597 this_obj->name = g_new (gunichar2, mono_string_length (name));
598 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
599 this_obj->name_len = mono_string_length (name);
602 this_obj->name = NULL;
605 /* the jit may read the compiled code of this function */
607 mono_thread_current (void)
612 thread = GET_CURRENT_OBJECT ();
613 g_message (G_GNUC_PRETTY_FUNCTION ": returning %p", thread);
617 return GET_CURRENT_OBJECT ();
621 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoThread *this,
622 int ms, HANDLE thread)
628 mono_monitor_enter (this->synch_lock);
629 this->state |= ThreadState_WaitSleepJoin;
630 mono_monitor_exit (this->synch_lock);
636 g_message (G_GNUC_PRETTY_FUNCTION ": joining thread handle %p, %d ms",
640 ret=WaitForSingleObjectEx (thread, ms, TRUE);
642 mono_monitor_enter (this->synch_lock);
643 this->state &= ~ThreadState_WaitSleepJoin;
644 mono_monitor_exit (this->synch_lock);
646 if(ret==WAIT_OBJECT_0) {
648 g_message (G_GNUC_PRETTY_FUNCTION ": join successful");
655 g_message (G_GNUC_PRETTY_FUNCTION ": join failed");
661 void ves_icall_System_Threading_Thread_SlotHash_store(MonoObject *data)
666 g_message(G_GNUC_PRETTY_FUNCTION ": Storing key %p", data);
669 /* Object location stored here */
670 TlsSetValue(slothash_key, data);
673 MonoObject *ves_icall_System_Threading_Thread_SlotHash_lookup(void)
679 data=TlsGetValue(slothash_key);
682 g_message(G_GNUC_PRETTY_FUNCTION ": Retrieved key %p", data);
688 /* FIXME: exitContext isnt documented */
689 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
695 MonoObject *waitHandle;
700 numhandles = mono_array_length(mono_handles);
701 handles = g_new0(HANDLE, numhandles);
703 if (wait_handle_os_handle_field == 0) {
704 /* Get the field os_handle which will contain the actual handle */
705 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");
706 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
709 for(i = 0; i < numhandles; i++) {
710 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
711 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
718 ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
722 if(ret==WAIT_FAILED) {
723 #ifdef THREAD_WAIT_DEBUG
724 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
725 GetCurrentThreadId ());
728 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
729 /* Do we want to try again if we get
730 * WAIT_IO_COMPLETION? The documentation for
731 * WaitHandle doesn't give any clues. (We'd have to
732 * fiddle with the timeout if we retry.)
734 #ifdef THREAD_WAIT_DEBUG
735 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
736 GetCurrentThreadId ());
744 /* FIXME: exitContext isnt documented */
745 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
751 MonoObject *waitHandle;
756 numhandles = mono_array_length(mono_handles);
757 handles = g_new0(HANDLE, numhandles);
759 if (wait_handle_os_handle_field == 0) {
760 /* Get the field os_handle which will contain the actual handle */
761 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");
762 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
765 for(i = 0; i < numhandles; i++) {
766 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
767 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
774 ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
778 #ifdef THREAD_WAIT_DEBUG
779 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) returning %d",
780 GetCurrentThreadId (), ret);
784 * These need to be here. See MSDN dos on WaitForMultipleObjects.
786 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
787 return ret - WAIT_OBJECT_0;
789 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
790 return ret - WAIT_ABANDONED_0;
797 /* FIXME: exitContext isnt documented */
798 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
804 #ifdef THREAD_WAIT_DEBUG
805 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) waiting for %p, %d ms",
806 GetCurrentThreadId (), handle, ms);
813 ret=WaitForSingleObjectEx (handle, ms, TRUE);
815 if(ret==WAIT_FAILED) {
816 #ifdef THREAD_WAIT_DEBUG
817 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
818 GetCurrentThreadId ());
821 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
822 /* Do we want to try again if we get
823 * WAIT_IO_COMPLETION? The documentation for
824 * WaitHandle doesn't give any clues. (We'd have to
825 * fiddle with the timeout if we retry.)
827 #ifdef THREAD_WAIT_DEBUG
828 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
829 GetCurrentThreadId ());
837 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
846 mutex = CreateMutex (NULL, owned, NULL);
848 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
850 if (GetLastError () == ERROR_ALREADY_EXISTS) {
858 void ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
861 ReleaseMutex(handle);
864 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name) {
867 return(CreateEvent (NULL, manual, initial,
868 name==NULL?NULL:mono_string_chars (name)));
871 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
874 return (SetEvent(handle));
877 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
880 return (ResetEvent(handle));
884 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
887 CloseHandle (handle);
890 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
894 return InterlockedIncrement (location);
897 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
904 EnterCriticalSection(&interlocked_mutex);
906 lowret = InterlockedIncrement((gint32 *) location);
908 highret = InterlockedIncrement((gint32 *) location + 1);
910 highret = *((gint32 *) location + 1);
912 LeaveCriticalSection(&interlocked_mutex);
914 return (gint64) highret << 32 | (gint64) lowret;
917 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
921 return InterlockedDecrement(location);
924 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
931 EnterCriticalSection(&interlocked_mutex);
933 lowret = InterlockedDecrement((gint32 *) location);
935 highret = InterlockedDecrement((gint32 *) location + 1);
937 highret = *((gint32 *) location + 1);
939 LeaveCriticalSection(&interlocked_mutex);
941 return (gint64) highret << 32 | (gint64) lowret;
944 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location1, gint32 value)
948 return InterlockedExchange(location1, value);
951 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location1, MonoObject *value)
955 return (MonoObject *) InterlockedExchangePointer((gpointer *) location1, value);
958 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location1, gfloat value)
960 IntFloatUnion val, ret;
965 ret.ival = InterlockedExchange((gint32 *) location1, val.ival);
970 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location1, gint32 value, gint32 comparand)
974 return InterlockedCompareExchange(location1, value, comparand);
977 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location1, MonoObject *value, MonoObject *comparand)
981 return (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location1, value, comparand);
984 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location1, gfloat value, gfloat comparand)
986 IntFloatUnion val, ret, cmp;
991 cmp.fval = comparand;
992 ret.ival = InterlockedCompareExchange((gint32 *) location1, val.ival, cmp.ival);
998 mono_thread_get_abort_signal (void)
1008 #endif /* __MINGW32__ */
1012 static guint32 interruption_request_apc (gpointer param)
1014 MonoException* exc = mono_thread_request_interruption (FALSE);
1015 if (exc) mono_raise_exception (exc);
1018 #endif /* __MINGW32__ */
1021 * signal_thread_state_change
1023 * Tells the thread that his state has changed and it has to enter the new
1024 * state as soon as possible.
1026 static void signal_thread_state_change (MonoThread *thread)
1029 QueueUserAPC (interruption_request_apc, thread->handle, NULL);
1031 /* fixme: store the state somewhere */
1032 #ifdef PTHREAD_POINTER_ID
1033 pthread_kill (GUINT_TO_POINTER(thread->tid), mono_thread_get_abort_signal ());
1035 pthread_kill (thread->tid, mono_thread_get_abort_signal ());
1037 #endif /* __MINGW32__ */
1041 ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
1043 MONO_ARCH_SAVE_REGS;
1045 mono_monitor_enter (thread->synch_lock);
1047 if ((thread->state & ThreadState_AbortRequested) != 0 ||
1048 (thread->state & ThreadState_StopRequested) != 0)
1050 mono_monitor_exit (thread->synch_lock);
1054 thread->state |= ThreadState_AbortRequested;
1055 thread->abort_state = state;
1056 thread->abort_exc = NULL;
1058 mono_monitor_exit (thread->synch_lock);
1061 g_message (G_GNUC_PRETTY_FUNCTION
1062 ": (%d) Abort requested for %p (%d)", GetCurrentThreadId (),
1063 thread, thread->tid);
1066 /* Make sure the thread is awake */
1067 ves_icall_System_Threading_Thread_Resume (thread);
1069 signal_thread_state_change (thread);
1073 ves_icall_System_Threading_Thread_ResetAbort (void)
1075 MonoThread *thread = mono_thread_current ();
1077 MONO_ARCH_SAVE_REGS;
1079 mono_monitor_enter (thread->synch_lock);
1081 thread->state &= ~ThreadState_AbortRequested;
1083 if (!thread->abort_exc) {
1084 const char *msg = "Unable to reset abort because no abort was requested";
1085 mono_monitor_exit (thread->synch_lock);
1086 mono_raise_exception (mono_get_exception_thread_state (msg));
1088 thread->abort_exc = NULL;
1089 thread->abort_state = NULL;
1092 mono_monitor_exit (thread->synch_lock);
1096 ves_icall_System_Threading_Thread_Suspend (MonoThread *thread)
1098 MONO_ARCH_SAVE_REGS;
1100 mono_monitor_enter (thread->synch_lock);
1102 if ((thread->state & ThreadState_Suspended) != 0 ||
1103 (thread->state & ThreadState_SuspendRequested) != 0 ||
1104 (thread->state & ThreadState_StopRequested) != 0)
1106 mono_monitor_exit (thread->synch_lock);
1110 thread->state |= ThreadState_SuspendRequested;
1111 mono_monitor_exit (thread->synch_lock);
1113 signal_thread_state_change (thread);
1117 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
1119 MONO_ARCH_SAVE_REGS;
1121 mono_monitor_enter (thread->synch_lock);
1123 if ((thread->state & ThreadState_SuspendRequested) != 0) {
1124 thread->state &= ~ThreadState_SuspendRequested;
1125 mono_monitor_exit (thread->synch_lock);
1129 if ((thread->state & ThreadState_Suspended) == 0)
1131 mono_monitor_exit (thread->synch_lock);
1135 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1137 /* Awake the thread */
1138 SetEvent (thread->suspend_event);
1140 mono_monitor_exit (thread->synch_lock);
1142 /* Wait for the thread to awake */
1143 WaitForSingleObject (thread->resume_event, INFINITE);
1144 CloseHandle (thread->resume_event);
1145 thread->resume_event = NULL;
1148 void mono_thread_stop (MonoThread *thread)
1150 mono_monitor_enter (thread->synch_lock);
1152 if ((thread->state & ThreadState_StopRequested) != 0 ||
1153 (thread->state & ThreadState_Stopped) != 0)
1155 mono_monitor_exit (thread->synch_lock);
1159 /* Make sure the thread is awake */
1160 ves_icall_System_Threading_Thread_Resume (thread);
1162 thread->state |= ThreadState_StopRequested;
1163 thread->state &= ~ThreadState_AbortRequested;
1165 mono_monitor_exit (thread->synch_lock);
1167 signal_thread_state_change (thread);
1171 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
1173 return *((volatile gint8 *) (ptr));
1177 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
1179 return *((volatile gint16 *) (ptr));
1183 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
1185 return *((volatile gint32 *) (ptr));
1189 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
1191 return *((volatile gint64 *) (ptr));
1195 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
1197 return (void *) *((volatile void **) ptr);
1201 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
1203 *((volatile gint8 *) ptr) = value;
1207 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
1209 *((volatile gint16 *) ptr) = value;
1213 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
1215 *((volatile gint32 *) ptr) = value;
1219 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
1221 *((volatile gint64 *) ptr) = value;
1225 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
1227 *((volatile void **) ptr) = value;
1230 void mono_thread_init (MonoThreadStartCB start_cb,
1231 MonoThreadAttachCB attach_cb)
1233 InitializeCriticalSection(&threads_mutex);
1234 InitializeCriticalSection(&interlocked_mutex);
1235 InitializeCriticalSection(&contexts_mutex);
1236 InitializeCriticalSection(&interruption_mutex);
1238 mono_init_static_data_info (&thread_static_info);
1239 mono_init_static_data_info (&context_static_info);
1241 current_object_key=TlsAlloc();
1243 g_message (G_GNUC_PRETTY_FUNCTION ": Allocated current_object_key %d",
1244 current_object_key);
1247 mono_thread_start_cb = start_cb;
1248 mono_thread_attach_cb = attach_cb;
1250 slothash_key=TlsAlloc();
1252 /* Get a pseudo handle to the current process. This is just a
1253 * kludge so that wapi can build a process handle if needed.
1254 * As a pseudo handle is returned, we don't need to clean
1257 GetCurrentProcess ();
1261 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
1263 mono_thread_cleanup = func;
1266 void mono_install_thread_callbacks (MonoThreadCallbacks *callbacks)
1268 mono_thread_callbacks = callbacks;
1272 static void print_tids (gpointer key, gpointer value, gpointer user)
1274 g_message ("Waiting for: %d", GPOINTER_TO_UINT(key));
1280 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
1281 MonoThread *threads[MAXIMUM_WAIT_OBJECTS];
1285 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
1290 g_message(G_GNUC_PRETTY_FUNCTION
1291 ": %d threads to wait for in this batch", wait->num);
1294 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
1296 if(ret==WAIT_FAILED) {
1297 /* See the comment in build_wait_tids() */
1299 g_message (G_GNUC_PRETTY_FUNCTION ": Wait failed");
1305 for(i=0; i<wait->num; i++) {
1306 guint32 tid=wait->threads[i]->tid;
1307 CloseHandle (wait->handles[i]);
1309 if(mono_g_hash_table_lookup (threads, GUINT_TO_POINTER(tid))!=NULL) {
1310 /* This thread must have been killed, because
1311 * it hasn't cleaned itself up. (It's just
1312 * possible that the thread exited before the
1313 * parent thread had a chance to store the
1314 * handle, and now there is another pointer to
1315 * the already-exited thread stored. In this
1316 * case, we'll just get two
1317 * mono_profiler_thread_end() calls for the
1322 g_message (G_GNUC_PRETTY_FUNCTION
1323 ": cleaning up after thread %d", tid);
1325 thread_cleanup (wait->threads[i]);
1330 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
1332 struct wait_data *wait=(struct wait_data *)user;
1334 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
1336 MonoThread *thread=(MonoThread *)value;
1338 /* Ignore background threads, we abort them later */
1339 if (thread->state & ThreadState_Background)
1340 return; /* just leave, ignore */
1342 if (mono_gc_is_finalizer_thread (thread))
1345 if (thread == mono_thread_current ())
1348 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1352 wait->handles[wait->num]=handle;
1353 wait->threads[wait->num]=thread;
1356 /* Just ignore the rest, we can't do anything with
1363 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
1365 struct wait_data *wait=(struct wait_data *)user;
1366 guint32 self = GetCurrentThreadId ();
1367 MonoThread *thread = (MonoThread *) value;
1370 /* The finalizer thread is not a background thread */
1371 if (thread->tid != self && thread->state & ThreadState_Background) {
1373 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1377 wait->handles[wait->num]=thread->handle;
1378 wait->threads[wait->num]=thread;
1381 if(thread->state & ThreadState_AbortRequested ||
1382 thread->state & ThreadState_Aborted) {
1384 g_message (G_GNUC_PRETTY_FUNCTION ": Thread id %d already aborting", thread->tid);
1390 g_print (G_GNUC_PRETTY_FUNCTION ": Aborting id: %d\n", thread->tid);
1392 mono_thread_stop (thread);
1396 return (thread->tid != self && !mono_gc_is_finalizer_thread (thread));
1399 void mono_thread_manage (void)
1401 struct wait_data *wait=g_new0 (struct wait_data, 1);
1403 /* join each thread that's still running */
1405 g_message(G_GNUC_PRETTY_FUNCTION ": Joining each running thread...");
1408 EnterCriticalSection (&threads_mutex);
1411 g_message(G_GNUC_PRETTY_FUNCTION ": No threads");
1413 LeaveCriticalSection (&threads_mutex);
1416 LeaveCriticalSection (&threads_mutex);
1419 EnterCriticalSection (&threads_mutex);
1421 g_message(G_GNUC_PRETTY_FUNCTION
1422 ":There are %d threads to join",
1423 mono_g_hash_table_size (threads));
1424 mono_g_hash_table_foreach (threads, print_tids, NULL);
1428 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
1429 LeaveCriticalSection (&threads_mutex);
1431 /* Something to wait for */
1432 wait_for_tids (wait, INFINITE);
1434 } while(wait->num>0);
1436 mono_thread_pool_cleanup ();
1438 EnterCriticalSection(&threads_mutex);
1441 * Remove everything but the finalizer thread and self.
1442 * Also abort all the background threads
1445 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
1447 LeaveCriticalSection(&threads_mutex);
1450 /* Something to wait for */
1451 wait_for_tids (wait, INFINITE);
1457 static void terminate_thread (gpointer key, gpointer value, gpointer user)
1459 MonoThread *thread=(MonoThread *)value;
1460 guint32 self=GPOINTER_TO_UINT (user);
1462 if(thread->tid!=self) {
1463 /*TerminateThread (thread->handle, -1);*/
1467 void mono_thread_abort_all_other_threads (void)
1469 guint32 self=GetCurrentThreadId ();
1471 EnterCriticalSection (&threads_mutex);
1473 g_message(G_GNUC_PRETTY_FUNCTION ":There are %d threads to abort",
1474 mono_g_hash_table_size (threads));
1475 mono_g_hash_table_foreach (threads, print_tids, NULL);
1478 mono_g_hash_table_foreach (threads, terminate_thread,
1479 GUINT_TO_POINTER (self));
1481 LeaveCriticalSection (&threads_mutex);
1485 * mono_thread_push_appdomain_ref:
1487 * Register that the current thread may have references to objects in domain
1488 * @domain on its stack. Each call to this function should be paired with a
1489 * call to pop_appdomain_ref.
1492 mono_thread_push_appdomain_ref (MonoDomain *domain)
1494 MonoThread *thread = mono_thread_current ();
1497 /* printf ("PUSH REF: %p -> %s.\n", thread, domain->friendly_name); */
1498 EnterCriticalSection (&threads_mutex);
1499 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
1500 LeaveCriticalSection (&threads_mutex);
1505 mono_thread_pop_appdomain_ref (void)
1507 MonoThread *thread = mono_thread_current ();
1510 /* printf ("POP REF: %p -> %s.\n", thread, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
1511 EnterCriticalSection (&threads_mutex);
1512 /* FIXME: How can the list be empty ? */
1513 if (thread->appdomain_refs)
1514 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
1515 LeaveCriticalSection (&threads_mutex);
1520 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
1523 EnterCriticalSection (&threads_mutex);
1524 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
1525 LeaveCriticalSection (&threads_mutex);
1529 typedef struct abort_appdomain_data {
1530 struct wait_data wait;
1532 } abort_appdomain_data;
1535 abort_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
1537 MonoThread *thread = (MonoThread*)value;
1538 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
1539 MonoDomain *domain = data->domain;
1541 if (mono_thread_has_appdomain_ref (thread, domain)) {
1542 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread, domain->friendly_name); */
1543 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1547 ves_icall_System_Threading_Thread_Abort (thread, NULL);
1549 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
1550 data->wait.handles [data->wait.num] = handle;
1551 data->wait.threads [data->wait.num] = thread;
1554 /* Just ignore the rest, we can't do anything with
1562 * mono_threads_abort_appdomain_threads:
1564 * Abort threads which has references to the given appdomain.
1567 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
1569 abort_appdomain_data user_data;
1572 /* printf ("ABORT BEGIN.\n"); */
1574 start_time = GetTickCount ();
1576 EnterCriticalSection (&threads_mutex);
1578 user_data.domain = domain;
1579 user_data.wait.num = 0;
1580 mono_g_hash_table_foreach (threads, abort_appdomain_thread, &user_data);
1581 LeaveCriticalSection (&threads_mutex);
1583 if (user_data.wait.num > 0)
1584 wait_for_tids (&user_data.wait, timeout);
1586 /* Update remaining time */
1587 timeout -= GetTickCount () - start_time;
1588 start_time = GetTickCount ();
1593 while (user_data.wait.num > 0);
1595 /* printf ("ABORT DONE.\n"); */
1601 * mono_thread_get_pending_exception:
1603 * Return an exception which needs to be raised when leaving a catch clause.
1604 * This is used for undeniable exception propagation.
1607 mono_thread_get_pending_exception (void)
1609 MonoThread *thread = mono_thread_current ();
1611 MONO_ARCH_SAVE_REGS;
1613 if (thread && thread->abort_exc) {
1615 * FIXME: Clear the abort exception and return an AppDomainUnloaded
1616 * exception if the thread no longer references a dying appdomain.
1618 thread->abort_exc->trace_ips = NULL;
1619 thread->abort_exc->stack_trace = NULL;
1620 return thread->abort_exc;
1626 #define NUM_STATIC_DATA_IDX 8
1627 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
1628 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
1633 * mono_alloc_static_data
1635 * Allocate memory blocks for storing threads or context static data
1638 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
1640 guint idx = (offset >> 24) - 1;
1643 gpointer* static_data = *static_data_ptr;
1646 static_data = GC_MALLOC (static_data_size [0]);
1648 static_data = g_malloc0 (static_data_size [0]);
1650 *static_data_ptr = static_data;
1651 static_data [0] = static_data;
1654 for (i = 1; i < idx; ++i) {
1655 if (static_data [i])
1658 static_data [i] = GC_MALLOC (static_data_size [i]);
1660 static_data [i] = g_malloc0 (static_data_size [i]);
1666 * mono_init_static_data_info
1668 * Initializes static data counters
1670 static void mono_init_static_data_info (StaticDataInfo *static_data)
1672 static_data->idx = 0;
1673 static_data->offset = 0;
1677 * mono_alloc_static_data_slot
1679 * Generates an offset for static data. static_data contains the counters
1680 * used to generate it.
1683 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
1687 if (!static_data->idx && !static_data->offset) {
1689 * we use the first chunk of the first allocation also as
1690 * an array for the rest of the data
1692 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
1694 static_data->offset += align - 1;
1695 static_data->offset &= ~(align - 1);
1696 if (static_data->offset + size >= static_data_size [static_data->idx]) {
1697 static_data->idx ++;
1698 g_assert (size <= static_data_size [static_data->idx]);
1700 * massive unloading and reloading of domains with thread-static
1701 * data may eventually exceed the allocated storage...
1702 * Need to check what the MS runtime does in that case.
1703 * Note that for each appdomain, we need to allocate a separate
1704 * thread data slot for security reasons. We could keep track
1705 * of the slots per-domain and when the domain is unloaded
1706 * out the slots on a sort of free list.
1708 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
1709 static_data->offset = 0;
1711 offset = static_data->offset | ((static_data->idx + 1) << 24);
1712 static_data->offset += size;
1717 * ensure thread static fields already allocated are valid for thread
1718 * This function is called when a thread is created or on thread attach.
1721 thread_adjust_static_data (MonoThread *thread)
1725 EnterCriticalSection (&threads_mutex);
1726 if (thread_static_info.offset || thread_static_info.idx > 0) {
1727 /* get the current allocated size */
1728 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
1729 mono_alloc_static_data (&(thread->static_data), offset);
1731 LeaveCriticalSection (&threads_mutex);
1735 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
1737 MonoThread *thread = value;
1738 guint32 offset = GPOINTER_TO_UINT (user);
1740 mono_alloc_static_data (&(thread->static_data), offset);
1744 * The offset for a special static variable is composed of three parts:
1745 * a bit that indicates the type of static data (0:thread, 1:context),
1746 * an index in the array of chunks of memory for the thread (thread->static_data)
1747 * and an offset in that chunk of mem. This allows allocating less memory in the
1752 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
1755 if (static_type == SPECIAL_STATIC_THREAD)
1757 EnterCriticalSection (&threads_mutex);
1758 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
1759 /* This can be called during startup */
1760 if (threads != NULL)
1761 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
1762 LeaveCriticalSection (&threads_mutex);
1766 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
1767 EnterCriticalSection (&contexts_mutex);
1768 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
1769 LeaveCriticalSection (&contexts_mutex);
1770 offset |= 0x80000000; /* Set the high bit to indicate context static data */
1776 mono_get_special_static_data (guint32 offset)
1778 /* The high bit means either thread (0) or static (1) data. */
1780 guint32 static_type = (offset & 0x80000000);
1783 offset &= 0x7fffffff;
1784 idx = (offset >> 24) - 1;
1786 if (static_type == 0)
1788 MonoThread *thread = mono_thread_current ();
1789 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
1793 /* Allocate static data block under demand, since we don't have a list
1796 MonoAppContext *context = mono_context_get ();
1797 if (!context->static_data || !context->static_data [idx]) {
1798 EnterCriticalSection (&contexts_mutex);
1799 mono_alloc_static_data (&(context->static_data), offset);
1800 LeaveCriticalSection (&contexts_mutex);
1802 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
1806 static void gc_stop_world (gpointer key, gpointer value, gpointer user)
1808 MonoThread *thread=(MonoThread *)value;
1809 guint32 self=GPOINTER_TO_UINT (user);
1812 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid);
1815 if(thread->tid==self)
1818 SuspendThread (thread->handle);
1821 void mono_gc_stop_world (void)
1823 guint32 self=GetCurrentThreadId ();
1826 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
1829 EnterCriticalSection (&threads_mutex);
1831 if (threads != NULL)
1832 mono_g_hash_table_foreach (threads, gc_stop_world, GUINT_TO_POINTER (self));
1834 LeaveCriticalSection (&threads_mutex);
1837 static void gc_start_world (gpointer key, gpointer value, gpointer user)
1839 MonoThread *thread=(MonoThread *)value;
1840 guint32 self=GPOINTER_TO_UINT (user);
1843 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid);
1846 if(thread->tid==self)
1849 ResumeThread (thread->handle);
1852 void mono_gc_start_world (void)
1854 guint32 self=GetCurrentThreadId ();
1857 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
1860 EnterCriticalSection (&threads_mutex);
1862 if (threads != NULL)
1863 mono_g_hash_table_foreach (threads, gc_start_world, GUINT_TO_POINTER (self));
1865 LeaveCriticalSection (&threads_mutex);
1869 static guint32 dummy_apc (gpointer param)
1875 * mono_thread_execute_interruption
1877 * Performs the operation that the requested thread state requires (abort,
1880 static MonoException* mono_thread_execute_interruption (MonoThread *thread)
1882 mono_monitor_enter (thread->synch_lock);
1884 if (thread->interruption_requested) {
1885 /* this will consume pending APC calls */
1886 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
1887 EnterCriticalSection (&interruption_mutex);
1888 thread_interruption_requested--;
1889 LeaveCriticalSection (&interruption_mutex);
1890 thread->interruption_requested = FALSE;
1893 if ((thread->state & ThreadState_AbortRequested) != 0) {
1894 thread->abort_exc = mono_get_exception_thread_abort ();
1895 mono_monitor_exit (thread->synch_lock);
1896 return thread->abort_exc;
1898 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
1899 thread->state &= ~ThreadState_SuspendRequested;
1900 thread->state |= ThreadState_Suspended;
1901 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1902 mono_monitor_exit (thread->synch_lock);
1904 WaitForSingleObject (thread->suspend_event, INFINITE);
1906 mono_monitor_enter (thread->synch_lock);
1907 CloseHandle (thread->suspend_event);
1908 thread->suspend_event = NULL;
1909 thread->state &= ~ThreadState_Suspended;
1911 /* The thread that requested the resume will have replaced this event
1912 * and will be waiting for it
1914 SetEvent (thread->resume_event);
1915 mono_monitor_exit (thread->synch_lock);
1918 else if ((thread->state & ThreadState_StopRequested) != 0) {
1919 /* FIXME: do this through the JIT? */
1920 mono_monitor_exit (thread->synch_lock);
1925 mono_monitor_exit (thread->synch_lock);
1930 * mono_thread_request_interruption
1932 * A signal handler can call this method to request the interruption of a
1933 * thread. The result of the interruption will depend on the current state of
1934 * the thread. If the result is an exception that needs to be throw, it is
1935 * provided as return value.
1937 MonoException* mono_thread_request_interruption (gboolean running_managed)
1939 MonoThread *thread = mono_thread_current ();
1941 /* The thread may already be stopping */
1945 mono_monitor_enter (thread->synch_lock);
1947 if (thread->interruption_requested) {
1948 mono_monitor_exit (thread->synch_lock);
1952 if (!running_managed) {
1953 /* Can't stop while in unmanaged code. Increase the global interruption
1954 request count. When exiting the unmanaged method the count will be
1955 checked and the thread will be interrupted. */
1957 EnterCriticalSection (&interruption_mutex);
1958 thread_interruption_requested++;
1959 LeaveCriticalSection (&interruption_mutex);
1961 thread->interruption_requested = TRUE;
1962 mono_monitor_exit (thread->synch_lock);
1964 /* this will awake the thread if it is in WaitForSingleObject
1966 QueueUserAPC (dummy_apc, thread->handle, NULL);
1971 mono_monitor_exit (thread->synch_lock);
1972 return mono_thread_execute_interruption (thread);
1976 gboolean mono_thread_interruption_requested ()
1978 if (thread_interruption_requested) {
1979 MonoThread *thread = mono_thread_current ();
1980 /* The thread may already be stopping */
1982 return (thread->interruption_requested);
1988 * Performs the interruption of the current thread, if one has been requested.
1990 void mono_thread_interruption_checkpoint ()
1992 MonoThread *thread = mono_thread_current ();
1994 /* The thread may already be stopping */
1998 if (thread->interruption_requested) {
1999 MonoException* exc = mono_thread_execute_interruption (thread);
2000 if (exc) mono_raise_exception (exc);
2005 * Returns the address of a flag that will be non-zero if an interruption has
2006 * been requested for a thread. The thread to interrupt may not be the current
2007 * thread, so an additional call to mono_thread_interruption_requested() or
2008 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
2011 gint32* mono_thread_interruption_request_flag ()
2013 return &thread_interruption_requested;
2016 #ifdef WITH_INCLUDED_LIBGC
2018 static void gc_push_all_stacks (gpointer key, gpointer value, gpointer user)
2020 MonoThread *thread=(MonoThread *)value;
2021 guint32 *selfp=(guint32 *)user, self = *selfp;
2024 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d - %p", self, thread->tid, thread->stack_ptr);
2027 if(thread->tid==self) {
2029 g_message (G_GNUC_PRETTY_FUNCTION ": %p - %p", selfp, thread->stack_ptr);
2031 GC_push_all_stack (selfp, thread->stack_ptr);
2035 #ifdef PLATFORM_WIN32
2036 GC_win32_push_thread_stack (thread->handle, thread->stack_ptr);
2038 mono_wapi_push_thread_stack (thread->handle, thread->stack_ptr);
2042 void mono_gc_push_all_stacks (void)
2044 guint32 self=GetCurrentThreadId ();
2047 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
2050 EnterCriticalSection (&threads_mutex);
2052 if (threads != NULL)
2053 mono_g_hash_table_foreach (threads, gc_push_all_stacks, &self);
2055 LeaveCriticalSection (&threads_mutex);
2058 #endif /* WITH_INCLUDED_LIBGC */