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;
80 /* function called at thread start */
81 static MonoThreadStartCB mono_thread_start_cb = NULL;
83 /* function called at thread attach */
84 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
86 /* function called at thread cleanup */
87 static MonoThreadCleanupFunc mono_thread_cleanup = NULL;
89 /* function called when a new thread has been created */
90 static MonoThreadCallbacks *mono_thread_callbacks = NULL;
92 /* The TLS key that holds the LocalDataStoreSlot hash in each thread */
93 static guint32 slothash_key = -1;
95 /* The default stack size for each thread */
96 static guint32 default_stacksize = 0;
98 static void thread_adjust_static_data (MonoThread *thread);
99 static void mono_init_static_data_info (StaticDataInfo *static_data);
100 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
102 /* Spin lock for InterlockedXXX 64 bit functions */
103 static CRITICAL_SECTION interlocked_mutex;
105 /* Controls access to interruption flag */
106 static CRITICAL_SECTION interruption_mutex;
108 /* global count of thread interruptions requested */
109 static gint32 thread_interruption_requested = 0;
112 /* handle_store() and handle_remove() manage the array of threads that
113 * still need to be waited for when the main thread exits.
115 static void handle_store(MonoThread *thread)
117 EnterCriticalSection(&threads_mutex);
120 g_message(G_GNUC_PRETTY_FUNCTION ": thread %p ID %d", thread,
125 threads=mono_g_hash_table_new(NULL, NULL);
128 /* We don't need to duplicate thread->handle, because it is
129 * only closed when the thread object is finalized by the GC.
131 mono_g_hash_table_insert(threads, GUINT_TO_POINTER(thread->tid), thread);
132 LeaveCriticalSection(&threads_mutex);
135 static void handle_remove(guint32 tid)
138 g_message(G_GNUC_PRETTY_FUNCTION ": thread ID %d", tid);
141 EnterCriticalSection(&threads_mutex);
144 mono_g_hash_table_remove (threads, GUINT_TO_POINTER(tid));
146 LeaveCriticalSection(&threads_mutex);
148 /* Don't close the handle here, wait for the object finalizer
149 * to do it. Otherwise, the following race condition applies:
151 * 1) Thread exits (and handle_remove() closes the handle)
153 * 2) Some other handle is reassigned the same slot
155 * 3) Another thread tries to join the first thread, and
156 * blocks waiting for the reassigned handle to be signalled
157 * (which might never happen). This is possible, because the
158 * thread calling Join() still has a reference to the first
163 static void thread_cleanup (MonoThread *thread)
165 if (!mono_monitor_enter (thread->synch_lock))
168 thread->state |= ThreadState_Stopped;
169 mono_monitor_exit (thread->synch_lock);
171 mono_profiler_thread_end (thread->tid);
172 handle_remove (thread->tid);
174 mono_thread_pop_appdomain_ref ();
176 if (mono_thread_cleanup)
177 mono_thread_cleanup (thread);
180 static guint32 start_wrapper(void *data)
182 struct StartInfo *start_info=(struct StartInfo *)data;
183 guint32 (*start_func)(void *);
186 MonoThread *thread=start_info->obj;
189 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Start wrapper",
190 GetCurrentThreadId ());
193 /* We can be sure start_info->obj->tid and
194 * start_info->obj->handle have been set, because the thread
195 * was created suspended, and these values were set before the
201 TlsSetValue (current_object_key, thread);
203 if (!mono_domain_set (start_info->domain, FALSE)) {
204 /* No point in raising an appdomain_unloaded exception here */
205 /* FIXME: Cleanup here */
209 start_func = start_info->func;
210 this = start_info->this;
212 /* This MUST be called before any managed code can be
213 * executed, as it calls the callback function that (for the
214 * jit) sets the lmf marker.
216 mono_thread_new_init (tid, &tid, start_func);
217 thread->stack_ptr = &tid;
220 g_message (G_GNUC_PRETTY_FUNCTION
221 ": (%d,%d) Setting thread stack to %p",
222 GetCurrentThreadId (), getpid (), thread->stack_ptr);
226 g_message (G_GNUC_PRETTY_FUNCTION
227 ": (%d) Setting current_object_key to %p",
228 GetCurrentThreadId (), thread);
231 mono_profiler_thread_start (tid);
233 if(thread->start_notify!=NULL) {
234 /* Let the thread that called Start() know we're
237 ReleaseSemaphore (thread->start_notify, 1, NULL);
242 /* Every thread references the appdomain which created it */
243 mono_thread_push_appdomain_ref (mono_domain_get ());
245 thread_adjust_static_data (thread);
246 #ifndef PLATFORM_WIN32
248 g_message (G_GNUC_PRETTY_FUNCTION "start_wrapper for %d\n", thread->tid);
250 pthread_cleanup_push ((void (*) (void *)) mono_thread_detach, thread);
254 #ifdef PLATFORM_WIN32
255 /* If the thread calls ExitThread at all, this remaining code
256 * will not be executed, but the main thread will eventually
257 * call thread_cleanup() on this thread's behalf.
261 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Start wrapper terminating",
262 GetCurrentThreadId ());
265 /* Remove the reference to the thread object in the TLS data,
266 * so the thread object can be finalized. This won't be
267 * reached if the thread threw an uncaught exception, so those
268 * thread handles will stay referenced :-( (This is due to
269 * missing support for scanning thread-specific data in the
270 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
273 TlsSetValue (current_object_key, NULL);
275 thread_cleanup (thread);
277 pthread_cleanup_pop (1);
283 void mono_thread_new_init (guint32 tid, gpointer stack_start, gpointer func)
285 if (mono_thread_start_cb) {
286 mono_thread_start_cb (tid, stack_start, func);
289 if (mono_thread_callbacks)
290 (* mono_thread_callbacks->thread_created) (tid, stack_start, func);
293 void mono_threads_set_default_stacksize (guint32 stacksize)
295 default_stacksize = stacksize;
298 guint32 mono_threads_get_default_stacksize (void)
300 return default_stacksize;
303 void mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
306 HANDLE thread_handle;
307 struct StartInfo *start_info;
310 thread=(MonoThread *)mono_object_new (domain,
311 mono_defaults.thread_class);
313 start_info=g_new0 (struct StartInfo, 1);
314 start_info->func = func;
315 start_info->obj = thread;
316 start_info->domain = domain;
317 start_info->this = arg;
319 /* Create suspended, so we can do some housekeeping before the thread
322 thread_handle = CreateThread(NULL, default_stacksize, start_wrapper, start_info,
323 CREATE_SUSPENDED, &tid);
325 g_message(G_GNUC_PRETTY_FUNCTION ": Started thread ID %d (handle %p)",
328 g_assert (thread_handle);
330 thread->handle=thread_handle;
333 thread->synch_lock=mono_object_new (domain, mono_defaults.object_class);
335 handle_store(thread);
337 ResumeThread (thread_handle);
341 mono_thread_attach (MonoDomain *domain)
344 HANDLE thread_handle;
347 if ((thread = mono_thread_current ())) {
348 /* Already attached */
352 thread = (MonoThread *)mono_object_new (domain,
353 mono_defaults.thread_class);
355 thread_handle = GetCurrentThread ();
356 g_assert (thread_handle);
358 tid=GetCurrentThreadId ();
360 thread->handle=thread_handle;
364 g_message(G_GNUC_PRETTY_FUNCTION ": Attached thread ID %d (handle %p)",
368 handle_store(thread);
371 g_message (G_GNUC_PRETTY_FUNCTION
372 ": (%d) Setting current_object_key to %p",
373 GetCurrentThreadId (), thread);
376 TlsSetValue (current_object_key, thread);
377 mono_domain_set (domain, TRUE);
379 thread_adjust_static_data (thread);
381 if (mono_thread_attach_cb) {
382 mono_thread_attach_cb (tid, &tid);
389 mono_thread_detach (MonoThread *thread)
391 g_return_if_fail (thread != NULL);
394 g_message (G_GNUC_PRETTY_FUNCTION "mono_thread_detach for %d\n", thread->tid);
396 TlsSetValue (current_object_key, NULL);
398 thread_cleanup (thread);
401 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
404 MonoMulticastDelegate *delegate = (MonoMulticastDelegate*)start;
405 guint32 (*start_func)(void *);
406 struct StartInfo *start_info;
414 g_message(G_GNUC_PRETTY_FUNCTION
415 ": Trying to start a new thread: this (%p) start (%p)",
419 im = mono_get_delegate_invoke (start->vtable->klass);
420 im = mono_marshal_get_delegate_invoke (im);
421 if (mono_thread_callbacks)
422 start_func = (* mono_thread_callbacks->thread_start_compile_func) (im);
424 start_func = mono_compile_method (im);
426 if(start_func==NULL) {
427 g_warning(G_GNUC_PRETTY_FUNCTION
428 ": Can't locate start method!");
431 /* This is freed in start_wrapper */
432 start_info = g_new0 (struct StartInfo, 1);
433 start_info->func = start_func;
434 start_info->this = delegate;
435 start_info->obj = this;
436 start_info->domain = mono_domain_get ();
438 this->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
439 if(this->start_notify==NULL) {
440 g_warning (G_GNUC_PRETTY_FUNCTION ": CreateSemaphore error 0x%x", GetLastError ());
444 thread=CreateThread(NULL, default_stacksize, start_wrapper, start_info,
445 CREATE_SUSPENDED, &tid);
447 g_warning(G_GNUC_PRETTY_FUNCTION
448 ": CreateThread error 0x%x", GetLastError());
455 /* Don't call handle_store() here, delay it to Start.
456 * We can't join a thread (trying to will just block
457 * forever) until it actually starts running, so don't
458 * store the handle till then.
462 g_message(G_GNUC_PRETTY_FUNCTION
463 ": Started thread ID %d (handle %p)", tid, thread);
470 void ves_icall_System_Threading_Thread_Thread_free_internal (MonoThread *this,
476 g_message (G_GNUC_PRETTY_FUNCTION ": Closing thread %p, handle %p",
480 CloseHandle (thread);
483 void ves_icall_System_Threading_Thread_Start_internal(MonoThread *this,
489 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Launching thread %p (%d)",
490 GetCurrentThreadId (), this, this->tid);
493 /* Only store the handle when the thread is about to be
494 * launched, to avoid the main thread deadlocking while trying
495 * to clean up a thread that will never be signalled.
499 if (mono_thread_callbacks)
500 (* mono_thread_callbacks->start_resume) (this->tid);
502 ResumeThread(thread);
504 if (mono_thread_callbacks)
505 (* mono_thread_callbacks->end_resume) (this->tid);
507 if(this->start_notify!=NULL) {
508 /* Wait for the thread to set up its TLS data etc, so
509 * theres no potential race condition if someone tries
510 * to look up the data believing the thread has
515 g_message(G_GNUC_PRETTY_FUNCTION
516 ": (%d) waiting for thread %p (%d) to start",
517 GetCurrentThreadId (), this, this->tid);
520 WaitForSingleObjectEx (this->start_notify, INFINITE, FALSE);
521 CloseHandle (this->start_notify);
522 this->start_notify=NULL;
526 g_message(G_GNUC_PRETTY_FUNCTION
527 ": (%d) Done launching thread %p (%d)",
528 GetCurrentThreadId (), this, this->tid);
532 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
534 MonoThread *thread = mono_thread_current ();
539 g_message(G_GNUC_PRETTY_FUNCTION ": Sleeping for %d ms", ms);
542 mono_monitor_enter (thread->synch_lock);
543 thread->state |= ThreadState_WaitSleepJoin;
544 mono_monitor_exit (thread->synch_lock);
548 mono_monitor_enter (thread->synch_lock);
549 thread->state &= ~ThreadState_WaitSleepJoin;
550 mono_monitor_exit (thread->synch_lock);
554 ves_icall_System_Threading_Thread_GetDomainID (void)
558 return mono_domain_get()->domain_id;
562 ves_icall_System_Threading_Thread_GetName_internal (MonoThread *this_obj)
567 return mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
571 ves_icall_System_Threading_Thread_SetName_internal (MonoThread *this_obj, MonoString *name)
574 g_free (this_obj->name);
576 this_obj->name = g_new (gunichar2, mono_string_length (name));
577 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
578 this_obj->name_len = mono_string_length (name);
581 this_obj->name = NULL;
585 mono_thread_current (void)
591 /* Find the current thread object */
592 thread=TlsGetValue (current_object_key);
595 g_message (G_GNUC_PRETTY_FUNCTION ": returning %p", thread);
601 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoThread *this,
602 int ms, HANDLE thread)
608 mono_monitor_enter (this->synch_lock);
609 this->state |= ThreadState_WaitSleepJoin;
610 mono_monitor_exit (this->synch_lock);
616 g_message (G_GNUC_PRETTY_FUNCTION ": joining thread handle %p, %d ms",
620 ret=WaitForSingleObjectEx (thread, ms, TRUE);
622 mono_monitor_enter (this->synch_lock);
623 this->state &= ~ThreadState_WaitSleepJoin;
624 mono_monitor_exit (this->synch_lock);
626 if(ret==WAIT_OBJECT_0) {
628 g_message (G_GNUC_PRETTY_FUNCTION ": join successful");
635 g_message (G_GNUC_PRETTY_FUNCTION ": join failed");
641 void ves_icall_System_Threading_Thread_SlotHash_store(MonoObject *data)
646 g_message(G_GNUC_PRETTY_FUNCTION ": Storing key %p", data);
649 /* Object location stored here */
650 TlsSetValue(slothash_key, data);
653 MonoObject *ves_icall_System_Threading_Thread_SlotHash_lookup(void)
659 data=TlsGetValue(slothash_key);
662 g_message(G_GNUC_PRETTY_FUNCTION ": Retrieved key %p", data);
668 /* FIXME: exitContext isnt documented */
669 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
675 MonoObject *waitHandle;
680 numhandles = mono_array_length(mono_handles);
681 handles = g_new0(HANDLE, numhandles);
683 if (wait_handle_os_handle_field == 0) {
684 /* Get the field os_handle which will contain the actual handle */
685 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");
686 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
689 for(i = 0; i < numhandles; i++) {
690 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
691 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
698 ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
702 if(ret==WAIT_FAILED) {
703 #ifdef THREAD_WAIT_DEBUG
704 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
705 GetCurrentThreadId ());
708 } else if(ret==WAIT_TIMEOUT) {
709 #ifdef THREAD_WAIT_DEBUG
710 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
711 GetCurrentThreadId ());
719 /* FIXME: exitContext isnt documented */
720 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
726 MonoObject *waitHandle;
731 numhandles = mono_array_length(mono_handles);
732 handles = g_new0(HANDLE, numhandles);
734 if (wait_handle_os_handle_field == 0) {
735 /* Get the field os_handle which will contain the actual handle */
736 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");
737 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
740 for(i = 0; i < numhandles; i++) {
741 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
742 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
749 ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
753 #ifdef THREAD_WAIT_DEBUG
754 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) returning %d",
755 GetCurrentThreadId (), ret);
759 * These need to be here. See MSDN dos on WaitForMultipleObjects.
761 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
762 return ret - WAIT_OBJECT_0;
764 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
765 return ret - WAIT_ABANDONED_0;
772 /* FIXME: exitContext isnt documented */
773 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
779 #ifdef THREAD_WAIT_DEBUG
780 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) waiting for %p, %d ms",
781 GetCurrentThreadId (), handle, ms);
788 ret=WaitForSingleObjectEx (handle, ms, TRUE);
790 if(ret==WAIT_FAILED) {
791 #ifdef THREAD_WAIT_DEBUG
792 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
793 GetCurrentThreadId ());
796 } else if(ret==WAIT_TIMEOUT) {
797 #ifdef THREAD_WAIT_DEBUG
798 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
799 GetCurrentThreadId ());
807 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name)
811 return(CreateMutex (NULL, owned,
812 name==NULL?NULL:mono_string_chars (name)));
815 void ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
818 ReleaseMutex(handle);
821 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name) {
824 return(CreateEvent (NULL, manual, initial,
825 name==NULL?NULL:mono_string_chars (name)));
828 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
831 return (SetEvent(handle));
834 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
837 return (ResetEvent(handle));
841 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
844 CloseHandle (handle);
847 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
851 return InterlockedIncrement (location);
854 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
861 EnterCriticalSection(&interlocked_mutex);
863 lowret = InterlockedIncrement((gint32 *) location);
865 highret = InterlockedIncrement((gint32 *) location + 1);
867 highret = *((gint32 *) location + 1);
869 LeaveCriticalSection(&interlocked_mutex);
871 return (gint64) highret << 32 | (gint64) lowret;
874 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
878 return InterlockedDecrement(location);
881 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
888 EnterCriticalSection(&interlocked_mutex);
890 lowret = InterlockedDecrement((gint32 *) location);
892 highret = InterlockedDecrement((gint32 *) location + 1);
894 highret = *((gint32 *) location + 1);
896 LeaveCriticalSection(&interlocked_mutex);
898 return (gint64) highret << 32 | (gint64) lowret;
901 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location1, gint32 value)
905 return InterlockedExchange(location1, value);
908 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location1, MonoObject *value)
912 return (MonoObject *) InterlockedExchangePointer((gpointer *) location1, value);
915 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location1, gfloat value)
917 IntFloatUnion val, ret;
922 ret.ival = InterlockedExchange((gint32 *) location1, val.ival);
927 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location1, gint32 value, gint32 comparand)
931 return InterlockedCompareExchange(location1, value, comparand);
934 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location1, MonoObject *value, MonoObject *comparand)
938 return (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location1, value, comparand);
941 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location1, gfloat value, gfloat comparand)
943 IntFloatUnion val, ret, cmp;
948 cmp.fval = comparand;
949 ret.ival = InterlockedCompareExchange((gint32 *) location1, val.ival, cmp.ival);
955 mono_thread_get_abort_signal (void)
965 #endif /* __MINGW32__ */
969 static guint32 interruption_request_apc (gpointer param)
971 MonoException* exc = mono_thread_request_interruption (FALSE);
972 if (exc) mono_raise_exception (exc);
975 #endif /* __MINGW32__ */
978 * signal_thread_state_change
980 * Tells the thread that his state has changed and it has to enter the new
981 * state as soon as possible.
983 static void signal_thread_state_change (MonoThread *thread)
986 QueueUserAPC (interruption_request_apc, thread->handle, NULL);
988 /* fixme: store the state somewhere */
989 #ifdef PTHREAD_POINTER_ID
990 pthread_kill (GUINT_TO_POINTER(thread->tid), mono_thread_get_abort_signal ());
992 pthread_kill (thread->tid, mono_thread_get_abort_signal ());
994 #endif /* __MINGW32__ */
998 ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
1000 MONO_ARCH_SAVE_REGS;
1002 mono_monitor_enter (thread->synch_lock);
1004 if ((thread->state & ThreadState_AbortRequested) != 0 ||
1005 (thread->state & ThreadState_StopRequested) != 0)
1007 mono_monitor_exit (thread->synch_lock);
1011 thread->state |= ThreadState_AbortRequested;
1012 thread->abort_state = state;
1013 thread->abort_exc = NULL;
1015 mono_monitor_exit (thread->synch_lock);
1018 g_message (G_GNUC_PRETTY_FUNCTION
1019 ": (%d) Abort requested for %p (%d)", GetCurrentThreadId (),
1020 thread, thread->tid);
1023 /* Make sure the thread is awake */
1024 ves_icall_System_Threading_Thread_Resume (thread);
1026 signal_thread_state_change (thread);
1030 ves_icall_System_Threading_Thread_ResetAbort (void)
1032 MonoThread *thread = mono_thread_current ();
1034 MONO_ARCH_SAVE_REGS;
1036 mono_monitor_enter (thread->synch_lock);
1038 thread->state &= ~ThreadState_AbortRequested;
1040 if (!thread->abort_exc) {
1041 const char *msg = "Unable to reset abort because no abort was requested";
1042 mono_monitor_exit (thread->synch_lock);
1043 mono_raise_exception (mono_get_exception_thread_state (msg));
1045 thread->abort_exc = NULL;
1046 thread->abort_state = NULL;
1049 mono_monitor_exit (thread->synch_lock);
1053 ves_icall_System_Threading_Thread_Suspend (MonoThread *thread)
1055 MONO_ARCH_SAVE_REGS;
1057 mono_monitor_enter (thread->synch_lock);
1059 if ((thread->state & ThreadState_Suspended) != 0 ||
1060 (thread->state & ThreadState_SuspendRequested) != 0 ||
1061 (thread->state & ThreadState_StopRequested) != 0)
1063 mono_monitor_exit (thread->synch_lock);
1067 thread->state |= ThreadState_SuspendRequested;
1068 mono_monitor_exit (thread->synch_lock);
1070 signal_thread_state_change (thread);
1074 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
1076 MONO_ARCH_SAVE_REGS;
1078 mono_monitor_enter (thread->synch_lock);
1080 if ((thread->state & ThreadState_SuspendRequested) != 0) {
1081 thread->state &= ~ThreadState_SuspendRequested;
1082 mono_monitor_exit (thread->synch_lock);
1086 if ((thread->state & ThreadState_Suspended) == 0)
1088 mono_monitor_exit (thread->synch_lock);
1092 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1094 /* Awake the thread */
1095 SetEvent (thread->suspend_event);
1097 mono_monitor_exit (thread->synch_lock);
1099 /* Wait for the thread to awake */
1100 WaitForSingleObject (thread->resume_event, INFINITE);
1101 CloseHandle (thread->resume_event);
1102 thread->resume_event = NULL;
1105 void mono_thread_stop (MonoThread *thread)
1107 mono_monitor_enter (thread->synch_lock);
1109 if ((thread->state & ThreadState_StopRequested) != 0 ||
1110 (thread->state & ThreadState_Stopped) != 0)
1112 mono_monitor_exit (thread->synch_lock);
1116 /* Make sure the thread is awake */
1117 ves_icall_System_Threading_Thread_Resume (thread);
1119 thread->state |= ThreadState_StopRequested;
1120 thread->state &= ~ThreadState_AbortRequested;
1122 mono_monitor_exit (thread->synch_lock);
1124 signal_thread_state_change (thread);
1128 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
1130 return *((volatile gint8 *) (ptr));
1134 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
1136 return *((volatile gint16 *) (ptr));
1140 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
1142 return *((volatile gint32 *) (ptr));
1146 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
1148 return *((volatile gint64 *) (ptr));
1152 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
1154 return (void *) *((volatile void **) ptr);
1158 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
1160 *((volatile gint8 *) ptr) = value;
1164 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
1166 *((volatile gint16 *) ptr) = value;
1170 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
1172 *((volatile gint32 *) ptr) = value;
1176 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
1178 *((volatile gint64 *) ptr) = value;
1182 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
1184 *((volatile void **) ptr) = value;
1187 void mono_thread_init (MonoThreadStartCB start_cb,
1188 MonoThreadAttachCB attach_cb)
1190 InitializeCriticalSection(&threads_mutex);
1191 InitializeCriticalSection(&interlocked_mutex);
1192 InitializeCriticalSection(&contexts_mutex);
1193 InitializeCriticalSection(&interruption_mutex);
1195 mono_init_static_data_info (&thread_static_info);
1196 mono_init_static_data_info (&context_static_info);
1198 current_object_key=TlsAlloc();
1200 g_message (G_GNUC_PRETTY_FUNCTION ": Allocated current_object_key %d",
1201 current_object_key);
1204 mono_thread_start_cb = start_cb;
1205 mono_thread_attach_cb = attach_cb;
1207 slothash_key=TlsAlloc();
1209 /* Get a pseudo handle to the current process. This is just a
1210 * kludge so that wapi can build a process handle if needed.
1211 * As a pseudo handle is returned, we don't need to clean
1214 GetCurrentProcess ();
1218 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
1220 mono_thread_cleanup = func;
1223 void mono_install_thread_callbacks (MonoThreadCallbacks *callbacks)
1225 mono_thread_callbacks = callbacks;
1229 static void print_tids (gpointer key, gpointer value, gpointer user)
1231 g_message ("Waiting for: %d", GPOINTER_TO_UINT(key));
1237 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
1238 MonoThread *threads[MAXIMUM_WAIT_OBJECTS];
1242 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
1247 g_message(G_GNUC_PRETTY_FUNCTION
1248 ": %d threads to wait for in this batch", wait->num);
1251 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
1253 if(ret==WAIT_FAILED) {
1254 /* See the comment in build_wait_tids() */
1256 g_message (G_GNUC_PRETTY_FUNCTION ": Wait failed");
1262 for(i=0; i<wait->num; i++) {
1263 guint32 tid=wait->threads[i]->tid;
1264 CloseHandle (wait->handles[i]);
1266 if(mono_g_hash_table_lookup (threads, GUINT_TO_POINTER(tid))!=NULL) {
1267 /* This thread must have been killed, because
1268 * it hasn't cleaned itself up. (It's just
1269 * possible that the thread exited before the
1270 * parent thread had a chance to store the
1271 * handle, and now there is another pointer to
1272 * the already-exited thread stored. In this
1273 * case, we'll just get two
1274 * mono_profiler_thread_end() calls for the
1279 g_message (G_GNUC_PRETTY_FUNCTION
1280 ": cleaning up after thread %d", tid);
1282 thread_cleanup (wait->threads[i]);
1287 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
1289 struct wait_data *wait=(struct wait_data *)user;
1291 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
1293 MonoThread *thread=(MonoThread *)value;
1295 /* Ignore background threads, we abort them later */
1296 if (thread->state & ThreadState_Background)
1297 return; /* just leave, ignore */
1299 if (mono_gc_is_finalizer_thread (thread))
1302 if (thread == mono_thread_current ())
1305 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1309 wait->handles[wait->num]=handle;
1310 wait->threads[wait->num]=thread;
1313 /* Just ignore the rest, we can't do anything with
1320 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
1322 struct wait_data *wait=(struct wait_data *)user;
1323 guint32 self = GetCurrentThreadId ();
1324 MonoThread *thread = (MonoThread *) value;
1327 /* The finalizer thread is not a background thread */
1328 if (thread->tid != self && thread->state & ThreadState_Background) {
1330 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1334 wait->handles[wait->num]=thread->handle;
1335 wait->threads[wait->num]=thread;
1338 if(thread->state & ThreadState_AbortRequested ||
1339 thread->state & ThreadState_Aborted) {
1341 g_message (G_GNUC_PRETTY_FUNCTION ": Thread id %d already aborting", thread->tid);
1347 g_print (G_GNUC_PRETTY_FUNCTION ": Aborting id: %d\n", thread->tid);
1349 mono_thread_stop (thread);
1353 return (thread->tid != self && !mono_gc_is_finalizer_thread (thread));
1356 void mono_thread_manage (void)
1358 struct wait_data *wait=g_new0 (struct wait_data, 1);
1360 /* join each thread that's still running */
1362 g_message(G_GNUC_PRETTY_FUNCTION ": Joining each running thread...");
1365 EnterCriticalSection (&threads_mutex);
1368 g_message(G_GNUC_PRETTY_FUNCTION ": No threads");
1370 LeaveCriticalSection (&threads_mutex);
1373 LeaveCriticalSection (&threads_mutex);
1376 EnterCriticalSection (&threads_mutex);
1378 g_message(G_GNUC_PRETTY_FUNCTION
1379 ":There are %d threads to join",
1380 mono_g_hash_table_size (threads));
1381 mono_g_hash_table_foreach (threads, print_tids, NULL);
1385 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
1386 LeaveCriticalSection (&threads_mutex);
1388 /* Something to wait for */
1389 wait_for_tids (wait, INFINITE);
1391 } while(wait->num>0);
1393 mono_thread_pool_cleanup ();
1395 EnterCriticalSection(&threads_mutex);
1398 * Remove everything but the finalizer thread and self.
1399 * Also abort all the background threads
1402 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
1404 LeaveCriticalSection(&threads_mutex);
1407 /* Something to wait for */
1408 wait_for_tids (wait, INFINITE);
1414 static void terminate_thread (gpointer key, gpointer value, gpointer user)
1416 MonoThread *thread=(MonoThread *)value;
1417 guint32 self=GPOINTER_TO_UINT (user);
1419 if(thread->tid!=self) {
1420 /*TerminateThread (thread->handle, -1);*/
1424 void mono_thread_abort_all_other_threads (void)
1426 guint32 self=GetCurrentThreadId ();
1428 EnterCriticalSection (&threads_mutex);
1430 g_message(G_GNUC_PRETTY_FUNCTION ":There are %d threads to abort",
1431 mono_g_hash_table_size (threads));
1432 mono_g_hash_table_foreach (threads, print_tids, NULL);
1435 mono_g_hash_table_foreach (threads, terminate_thread,
1436 GUINT_TO_POINTER (self));
1438 LeaveCriticalSection (&threads_mutex);
1442 * mono_thread_push_appdomain_ref:
1444 * Register that the current thread may have references to objects in domain
1445 * @domain on its stack. Each call to this function should be paired with a
1446 * call to pop_appdomain_ref.
1449 mono_thread_push_appdomain_ref (MonoDomain *domain)
1451 MonoThread *thread = mono_thread_current ();
1454 //printf ("PUSH REF: %p -> %s.\n", thread, domain->friendly_name);
1455 EnterCriticalSection (&threads_mutex);
1456 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
1457 LeaveCriticalSection (&threads_mutex);
1462 mono_thread_pop_appdomain_ref (void)
1464 MonoThread *thread = mono_thread_current ();
1467 //printf ("POP REF: %p -> %s.\n", thread, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name);
1468 EnterCriticalSection (&threads_mutex);
1469 // FIXME: How can the list be empty ?
1470 if (thread->appdomain_refs)
1471 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
1472 LeaveCriticalSection (&threads_mutex);
1477 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
1480 EnterCriticalSection (&threads_mutex);
1481 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
1482 LeaveCriticalSection (&threads_mutex);
1486 typedef struct abort_appdomain_data {
1487 struct wait_data wait;
1489 } abort_appdomain_data;
1492 abort_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
1494 MonoThread *thread = (MonoThread*)value;
1495 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
1496 MonoDomain *domain = data->domain;
1498 if (mono_thread_has_appdomain_ref (thread, domain)) {
1499 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread, domain->friendly_name); */
1500 ves_icall_System_Threading_Thread_Abort (thread, NULL);
1502 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
1503 data->wait.handles [data->wait.num] = thread->handle;
1504 data->wait.threads [data->wait.num] = thread;
1507 /* Just ignore the rest, we can't do anything with
1515 * mono_threads_abort_appdomain_threads:
1517 * Abort threads which has references to the given appdomain.
1520 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
1522 abort_appdomain_data user_data;
1525 /* printf ("ABORT BEGIN.\n"); */
1527 start_time = GetTickCount ();
1529 EnterCriticalSection (&threads_mutex);
1531 user_data.domain = domain;
1532 user_data.wait.num = 0;
1533 mono_g_hash_table_foreach (threads, abort_appdomain_thread, &user_data);
1534 LeaveCriticalSection (&threads_mutex);
1536 if (user_data.wait.num > 0)
1537 wait_for_tids (&user_data.wait, timeout);
1539 /* Update remaining time */
1540 timeout -= GetTickCount () - start_time;
1541 start_time = GetTickCount ();
1546 while (user_data.wait.num > 0);
1548 /* printf ("ABORT DONE.\n"); */
1554 * mono_thread_get_pending_exception:
1556 * Return an exception which needs to be raised when leaving a catch clause.
1557 * This is used for undeniable exception propagation.
1560 mono_thread_get_pending_exception (void)
1562 MonoThread *thread = mono_thread_current ();
1564 MONO_ARCH_SAVE_REGS;
1566 if (thread && thread->abort_exc) {
1568 * FIXME: Clear the abort exception and return an AppDomainUnloaded
1569 * exception if the thread no longer references a dying appdomain.
1571 thread->abort_exc->trace_ips = NULL;
1572 thread->abort_exc->stack_trace = NULL;
1573 return thread->abort_exc;
1579 #define NUM_STATIC_DATA_IDX 8
1580 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
1581 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
1586 * mono_alloc_static_data
1588 * Allocate memory blocks for storing threads or context static data
1591 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
1593 guint idx = (offset >> 24) - 1;
1596 gpointer* static_data = *static_data_ptr;
1599 static_data = GC_MALLOC (static_data_size [0]);
1601 static_data = g_malloc0 (static_data_size [0]);
1603 *static_data_ptr = static_data;
1604 static_data [0] = static_data;
1607 for (i = 1; i < idx; ++i) {
1608 if (static_data [i])
1611 static_data [i] = GC_MALLOC (static_data_size [i]);
1613 static_data [i] = g_malloc0 (static_data_size [i]);
1619 * mono_init_static_data_info
1621 * Initializes static data counters
1623 static void mono_init_static_data_info (StaticDataInfo *static_data)
1625 static_data->idx = 0;
1626 static_data->offset = 0;
1630 * mono_alloc_static_data_slot
1632 * Generates an offset for static data. static_data contains the counters
1633 * used to generate it.
1636 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
1640 if (!static_data->idx && !static_data->offset) {
1642 * we use the first chunk of the first allocation also as
1643 * an array for the rest of the data
1645 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
1647 static_data->offset += align - 1;
1648 static_data->offset &= ~(align - 1);
1649 if (static_data->offset + size >= static_data_size [static_data->idx]) {
1650 static_data->idx ++;
1651 g_assert (size <= static_data_size [static_data->idx]);
1653 * massive unloading and reloading of domains with thread-static
1654 * data may eventually exceed the allocated storage...
1655 * Need to check what the MS runtime does in that case.
1656 * Note that for each appdomain, we need to allocate a separate
1657 * thread data slot for security reasons. We could keep track
1658 * of the slots per-domain and when the domain is unloaded
1659 * out the slots on a sort of free list.
1661 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
1662 static_data->offset = 0;
1664 offset = static_data->offset | ((static_data->idx + 1) << 24);
1665 static_data->offset += size;
1670 * ensure thread static fields already allocated are valid for thread
1671 * This function is called when a thread is created or on thread attach.
1674 thread_adjust_static_data (MonoThread *thread)
1678 EnterCriticalSection (&threads_mutex);
1679 if (thread_static_info.offset || thread_static_info.idx > 0) {
1680 /* get the current allocated size */
1681 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
1682 mono_alloc_static_data (&(thread->static_data), offset);
1684 LeaveCriticalSection (&threads_mutex);
1688 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
1690 MonoThread *thread = value;
1691 guint32 offset = GPOINTER_TO_UINT (user);
1693 mono_alloc_static_data (&(thread->static_data), offset);
1697 * The offset for a special static variable is composed of three parts:
1698 * a bit that indicates the type of static data (0:thread, 1:context),
1699 * an index in the array of chunks of memory for the thread (thread->static_data)
1700 * and an offset in that chunk of mem. This allows allocating less memory in the
1705 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
1708 if (static_type == SPECIAL_STATIC_THREAD)
1710 EnterCriticalSection (&threads_mutex);
1711 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
1712 /* This can be called during startup */
1713 if (threads != NULL)
1714 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
1715 LeaveCriticalSection (&threads_mutex);
1719 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
1720 EnterCriticalSection (&contexts_mutex);
1721 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
1722 LeaveCriticalSection (&contexts_mutex);
1723 offset |= 0x80000000; // Set the high bit to indicate context static data
1729 mono_get_special_static_data (guint32 offset)
1731 // The high bit means either thread (0) or static (1) data.
1733 guint32 static_type = (offset & 0x80000000);
1736 offset &= 0x7fffffff;
1737 idx = (offset >> 24) - 1;
1739 if (static_type == 0)
1741 MonoThread *thread = mono_thread_current ();
1742 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
1746 // Allocate static data block under demand, since we don't have a list
1748 MonoAppContext *context = mono_context_get ();
1749 if (!context->static_data || !context->static_data [idx]) {
1750 EnterCriticalSection (&contexts_mutex);
1751 mono_alloc_static_data (&(context->static_data), offset);
1752 LeaveCriticalSection (&contexts_mutex);
1754 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
1758 static void gc_stop_world (gpointer key, gpointer value, gpointer user)
1760 MonoThread *thread=(MonoThread *)value;
1761 guint32 self=GPOINTER_TO_UINT (user);
1764 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid);
1767 if(thread->tid==self)
1770 SuspendThread (thread->handle);
1773 void mono_gc_stop_world (void)
1775 guint32 self=GetCurrentThreadId ();
1778 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
1781 EnterCriticalSection (&threads_mutex);
1783 if (threads != NULL)
1784 mono_g_hash_table_foreach (threads, gc_stop_world, GUINT_TO_POINTER (self));
1786 LeaveCriticalSection (&threads_mutex);
1789 static void gc_start_world (gpointer key, gpointer value, gpointer user)
1791 MonoThread *thread=(MonoThread *)value;
1792 guint32 self=GPOINTER_TO_UINT (user);
1795 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid);
1798 if(thread->tid==self)
1801 ResumeThread (thread->handle);
1804 void mono_gc_start_world (void)
1806 guint32 self=GetCurrentThreadId ();
1809 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
1812 EnterCriticalSection (&threads_mutex);
1814 if (threads != NULL)
1815 mono_g_hash_table_foreach (threads, gc_start_world, GUINT_TO_POINTER (self));
1817 LeaveCriticalSection (&threads_mutex);
1821 static guint32 dummy_apc (gpointer param)
1827 * mono_thread_execute_interruption
1829 * Performs the operation that the requested thread state requires (abort,
1832 static MonoException* mono_thread_execute_interruption (MonoThread *thread)
1834 mono_monitor_enter (thread->synch_lock);
1836 if (thread->interruption_requested) {
1837 /* this will consume pending APC calls */
1838 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
1839 EnterCriticalSection (&interruption_mutex);
1840 thread_interruption_requested--;
1841 LeaveCriticalSection (&interruption_mutex);
1842 thread->interruption_requested = FALSE;
1845 if ((thread->state & ThreadState_AbortRequested) != 0) {
1846 thread->abort_exc = mono_get_exception_thread_abort ();
1847 mono_monitor_exit (thread->synch_lock);
1848 return thread->abort_exc;
1850 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
1851 thread->state &= ~ThreadState_SuspendRequested;
1852 thread->state |= ThreadState_Suspended;
1853 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1854 mono_monitor_exit (thread->synch_lock);
1856 WaitForSingleObject (thread->suspend_event, INFINITE);
1858 mono_monitor_enter (thread->synch_lock);
1859 CloseHandle (thread->suspend_event);
1860 thread->suspend_event = NULL;
1861 thread->state &= ~ThreadState_Suspended;
1863 /* The thread that requested the resume will have replaced this event
1864 * and will be waiting for it
1866 SetEvent (thread->resume_event);
1867 mono_monitor_exit (thread->synch_lock);
1870 else if ((thread->state & ThreadState_StopRequested) != 0) {
1871 /* FIXME: do this through the JIT? */
1872 mono_monitor_exit (thread->synch_lock);
1877 mono_monitor_exit (thread->synch_lock);
1882 * mono_thread_request_interruption
1884 * A signal handler can call this method to request the interruption of a
1885 * thread. The result of the interruption will depend on the current state of
1886 * the thread. If the result is an exception that needs to be throw, it is
1887 * provided as return value.
1889 MonoException* mono_thread_request_interruption (gboolean running_managed)
1891 MonoThread *thread = mono_thread_current ();
1893 /* The thread may already be stopping */
1897 mono_monitor_enter (thread->synch_lock);
1899 if (thread->interruption_requested) {
1900 mono_monitor_exit (thread->synch_lock);
1904 if (!running_managed) {
1905 /* Can't stop while in unmanaged code. Increase the global interruption
1906 request count. When exiting the unmanaged method the count will be
1907 checked and the thread will be interrupted. */
1909 EnterCriticalSection (&interruption_mutex);
1910 thread_interruption_requested++;
1911 LeaveCriticalSection (&interruption_mutex);
1913 thread->interruption_requested = TRUE;
1914 mono_monitor_exit (thread->synch_lock);
1916 /* this will awake the thread if it is in WaitForSingleObject
1918 QueueUserAPC (dummy_apc, thread->handle, NULL);
1923 mono_monitor_exit (thread->synch_lock);
1924 return mono_thread_execute_interruption (thread);
1928 gboolean mono_thread_interruption_requested ()
1930 if (thread_interruption_requested) {
1931 MonoThread *thread = mono_thread_current ();
1932 /* The thread may already be stopping */
1934 return (thread->interruption_requested);
1940 * Performs the interruption of the current thread, if one has been requested.
1942 void mono_thread_interruption_checkpoint ()
1944 MonoThread *thread = mono_thread_current ();
1946 /* The thread may already be stopping */
1950 if (thread->interruption_requested) {
1951 MonoException* exc = mono_thread_execute_interruption (thread);
1952 if (exc) mono_raise_exception (exc);
1957 * Returns the address of a flag that will be non-zero if an interruption has
1958 * been requested for a thread. The thread to interrupt may not be the current
1959 * thread, so an additional call to mono_thread_interruption_requested() or
1960 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
1963 gint32* mono_thread_interruption_request_flag ()
1965 return &thread_interruption_requested;
1968 #ifdef WITH_INCLUDED_LIBGC
1970 static void gc_push_all_stacks (gpointer key, gpointer value, gpointer user)
1972 MonoThread *thread=(MonoThread *)value;
1973 guint32 *selfp=(guint32 *)user, self = *selfp;
1976 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d - %p", self, thread->tid, thread->stack_ptr);
1979 if(thread->tid==self) {
1981 g_message (G_GNUC_PRETTY_FUNCTION ": %p - %p", selfp, thread->stack_ptr);
1983 GC_push_all_stack (selfp, thread->stack_ptr);
1987 #ifdef PLATFORM_WIN32
1988 GC_win32_push_thread_stack (thread->handle, thread->stack_ptr);
1990 mono_wapi_push_thread_stack (thread->handle, thread->stack_ptr);
1994 void mono_gc_push_all_stacks (void)
1996 guint32 self=GetCurrentThreadId ();
1999 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
2002 EnterCriticalSection (&threads_mutex);
2004 if (threads != NULL)
2005 mono_g_hash_table_foreach (threads, gc_push_all_stacks, &self);
2007 LeaveCriticalSection (&threads_mutex);
2010 #endif /* WITH_INCLUDED_LIBGC */