2 * threadpool.c: Microsoft threadpool runtime support
5 * Ludovic Henry (ludovic.henry@xamarin.com)
7 * Copyright 2015 Xamarin, Inc (http://www.xamarin.com)
8 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
12 // Copyright (c) Microsoft. All rights reserved.
13 // Licensed under the MIT license. See LICENSE file in the project root for full license information.
16 // - src/vm/comthreadpool.cpp
17 // - src/vm/win32threadpoolcpp
18 // - src/vm/threadpoolrequest.cpp
19 // - src/vm/hillclimbing.cpp
21 // Ported from C++ to C and adjusted to Mono runtime
24 #define _USE_MATH_DEFINES // needed by MSVC to define math constants
29 #include <mono/metadata/class-internals.h>
30 #include <mono/metadata/exception.h>
31 #include <mono/metadata/gc-internals.h>
32 #include <mono/metadata/object.h>
33 #include <mono/metadata/object-internals.h>
34 #include <mono/metadata/threadpool.h>
35 #include <mono/metadata/threadpool-worker.h>
36 #include <mono/metadata/threadpool-io.h>
37 #include <mono/metadata/w32event.h>
38 #include <mono/utils/atomic.h>
39 #include <mono/utils/mono-compiler.h>
40 #include <mono/utils/mono-complex.h>
41 #include <mono/utils/mono-lazy-init.h>
42 #include <mono/utils/mono-logger.h>
43 #include <mono/utils/mono-logger-internals.h>
44 #include <mono/utils/mono-proclib.h>
45 #include <mono/utils/mono-threads.h>
46 #include <mono/utils/mono-time.h>
47 #include <mono/utils/refcount.h>
51 /* Number of outstanding jobs */
52 gint32 outstanding_request;
53 /* Number of currently executing jobs */
54 gint32 threadpool_jobs;
55 /* Signalled when threadpool_jobs + outstanding_request is 0 */
56 /* Protected by threadpool.domains_lock */
57 MonoCoopCond cleanup_cond;
62 gint16 starting; /* starting, but not yet in worker_callback */
63 gint16 working; /* executing worker_callback */
71 GPtrArray *domains; // ThreadPoolDomain* []
72 MonoCoopMutex domains_lock;
74 GPtrArray *threads; // MonoInternalThread* []
75 MonoCoopMutex threads_lock;
76 MonoCoopCond threads_exit_cond;
78 ThreadPoolCounter counters;
84 static mono_lazy_init_t status = MONO_LAZY_INIT_STATUS_NOT_INITIALIZED;
86 static ThreadPool threadpool;
88 #define COUNTER_ATOMIC(var,block) \
90 ThreadPoolCounter __old; \
92 (var) = __old = COUNTER_READ (); \
94 if (!(counter._.starting >= 0)) \
95 g_error ("%s: counter._.starting = %d, but should be >= 0", __func__, counter._.starting); \
96 if (!(counter._.working >= 0)) \
97 g_error ("%s: counter._.working = %d, but should be >= 0", __func__, counter._.working); \
98 } while (InterlockedCompareExchange (&threadpool.counters.as_gint32, (var).as_gint32, __old.as_gint32) != __old.as_gint32); \
101 static inline ThreadPoolCounter
104 ThreadPoolCounter counter;
105 counter.as_gint32 = InterlockedRead (&threadpool.counters.as_gint32);
112 mono_coop_mutex_lock (&threadpool.domains_lock);
116 domains_unlock (void)
118 mono_coop_mutex_unlock (&threadpool.domains_lock);
122 destroy (gpointer unused)
125 g_ptr_array_free (threadpool.domains, TRUE);
126 mono_coop_mutex_destroy (&threadpool.domains_lock);
128 g_ptr_array_free (threadpool.threads, TRUE);
129 mono_coop_mutex_destroy (&threadpool.threads_lock);
130 mono_coop_cond_destroy (&threadpool.threads_exit_cond);
137 g_assert (sizeof (ThreadPoolCounter) == sizeof (gint32));
139 mono_refcount_init (&threadpool, destroy);
141 threadpool.domains = g_ptr_array_new ();
142 mono_coop_mutex_init (&threadpool.domains_lock);
144 threadpool.threads = g_ptr_array_new ();
145 mono_coop_mutex_init (&threadpool.threads_lock);
146 mono_coop_cond_init (&threadpool.threads_exit_cond);
148 threadpool.limit_io_min = mono_cpu_count ();
149 threadpool.limit_io_max = CLAMP (threadpool.limit_io_min * 100, MIN (threadpool.limit_io_min, 200), MAX (threadpool.limit_io_min, 200));
151 mono_threadpool_worker_init ();
158 MonoInternalThread *current;
160 /* we make the assumption along the code that we are
161 * cleaning up only if the runtime is shutting down */
162 g_assert (mono_runtime_is_shutting_down ());
164 current = mono_thread_internal_current ();
166 mono_coop_mutex_lock (&threadpool.threads_lock);
168 /* stop all threadpool.threads */
169 for (i = 0; i < threadpool.threads->len; ++i) {
170 MonoInternalThread *thread = (MonoInternalThread*) g_ptr_array_index (threadpool.threads, i);
171 if (thread != current)
172 mono_thread_internal_abort (thread);
175 mono_coop_mutex_unlock (&threadpool.threads_lock);
178 /* give a chance to the other threads to exit */
179 mono_thread_info_yield ();
181 mono_coop_mutex_lock (&threadpool.threads_lock);
184 if (threadpool.threads->len == 0)
187 if (threadpool.threads->len == 1 && g_ptr_array_index (threadpool.threads, 0) == current) {
188 /* We are waiting on ourselves */
192 mono_coop_cond_wait (&threadpool.threads_exit_cond, &threadpool.threads_lock);
195 mono_coop_mutex_unlock (&threadpool.threads_lock);
198 mono_threadpool_worker_cleanup ();
200 mono_refcount_dec (&threadpool);
204 mono_threadpool_enqueue_work_item (MonoDomain *domain, MonoObject *work_item, MonoError *error)
206 static MonoClass *threadpool_class = NULL;
207 static MonoMethod *unsafe_queue_custom_work_item_method = NULL;
208 MonoDomain *current_domain;
212 mono_error_init (error);
213 g_assert (work_item);
215 if (!threadpool_class)
216 threadpool_class = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "ThreadPool");
218 if (!unsafe_queue_custom_work_item_method)
219 unsafe_queue_custom_work_item_method = mono_class_get_method_from_name (threadpool_class, "UnsafeQueueCustomWorkItem", 2);
220 g_assert (unsafe_queue_custom_work_item_method);
224 args [0] = (gpointer) work_item;
225 args [1] = (gpointer) &f;
227 current_domain = mono_domain_get ();
228 if (current_domain == domain) {
229 mono_runtime_invoke_checked (unsafe_queue_custom_work_item_method, NULL, args, error);
230 return_val_if_nok (error, FALSE);
232 mono_thread_push_appdomain_ref (domain);
233 if (mono_domain_set (domain, FALSE)) {
234 mono_runtime_invoke_checked (unsafe_queue_custom_work_item_method, NULL, args, error);
235 if (!is_ok (error)) {
236 mono_thread_pop_appdomain_ref ();
239 mono_domain_set (current_domain, TRUE);
241 mono_thread_pop_appdomain_ref ();
246 /* LOCKING: domains_lock must be held. */
247 static ThreadPoolDomain *
248 tpdomain_create (MonoDomain *domain)
250 ThreadPoolDomain *tpdomain;
252 tpdomain = g_new0 (ThreadPoolDomain, 1);
253 tpdomain->domain = domain;
254 mono_coop_cond_init (&tpdomain->cleanup_cond);
256 g_ptr_array_add (threadpool.domains, tpdomain);
261 /* LOCKING: domains_lock must be held. */
263 tpdomain_remove (ThreadPoolDomain *tpdomain)
266 return g_ptr_array_remove (threadpool.domains, tpdomain);
269 /* LOCKING: domains_lock must be held */
270 static ThreadPoolDomain *
271 tpdomain_get (MonoDomain *domain)
277 for (i = 0; i < threadpool.domains->len; ++i) {
278 ThreadPoolDomain *tpdomain;
280 tpdomain = (ThreadPoolDomain *)g_ptr_array_index (threadpool.domains, i);
281 if (tpdomain->domain == domain)
289 tpdomain_free (ThreadPoolDomain *tpdomain)
294 /* LOCKING: domains_lock must be held */
295 static ThreadPoolDomain *
296 tpdomain_get_next (ThreadPoolDomain *current)
298 ThreadPoolDomain *tpdomain = NULL;
301 len = threadpool.domains->len;
303 gint i, current_idx = -1;
305 for (i = 0; i < len; ++i) {
306 if (current == g_ptr_array_index (threadpool.domains, i)) {
312 for (i = current_idx + 1; i < len + current_idx + 1; ++i) {
313 ThreadPoolDomain *tmp = (ThreadPoolDomain *)g_ptr_array_index (threadpool.domains, i % len);
314 if (tmp->outstanding_request > 0) {
325 try_invoke_perform_wait_callback (MonoObject** exc, MonoError *error)
327 HANDLE_FUNCTION_ENTER ();
328 mono_error_init (error);
329 MonoObject *res = mono_runtime_try_invoke (mono_defaults.threadpool_perform_wait_callback_method, NULL, NULL, exc, error);
330 HANDLE_FUNCTION_RETURN_VAL (res);
334 worker_callback (gpointer unused)
337 ThreadPoolDomain *tpdomain, *previous_tpdomain;
338 ThreadPoolCounter counter;
339 MonoInternalThread *thread;
341 thread = mono_thread_internal_current ();
343 COUNTER_ATOMIC (counter, {
344 if (!(counter._.working < 32767 /* G_MAXINT16 */))
345 g_error ("%s: counter._.working = %d, but should be < 32767", __func__, counter._.working);
347 counter._.starting --;
348 counter._.working ++;
351 if (mono_runtime_is_shutting_down ()) {
352 COUNTER_ATOMIC (counter, {
353 counter._.working --;
356 mono_refcount_dec (&threadpool);
360 mono_coop_mutex_lock (&threadpool.threads_lock);
361 g_ptr_array_add (threadpool.threads, thread);
362 mono_coop_mutex_unlock (&threadpool.threads_lock);
365 * This is needed so there is always an lmf frame in the runtime invoke call below,
366 * so ThreadAbortExceptions are caught even if the thread is in native code.
368 mono_defaults.threadpool_perform_wait_callback_method->save_lmf = TRUE;
372 previous_tpdomain = NULL;
374 while (!mono_runtime_is_shutting_down ()) {
375 gboolean retire = FALSE;
377 if (thread->state & (ThreadState_AbortRequested | ThreadState_SuspendRequested)) {
379 if (mono_thread_interruption_checkpoint ()) {
386 tpdomain = tpdomain_get_next (previous_tpdomain);
390 tpdomain->outstanding_request --;
391 g_assert (tpdomain->outstanding_request >= 0);
393 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] worker running in domain %p (outstanding requests %d)",
394 mono_native_thread_id_get (), tpdomain->domain, tpdomain->outstanding_request);
396 g_assert (tpdomain->threadpool_jobs >= 0);
397 tpdomain->threadpool_jobs ++;
401 mono_thread_set_name_internal (thread, mono_string_new (mono_get_root_domain (), "Threadpool worker"), FALSE, TRUE, &error);
402 mono_error_assert_ok (&error);
404 mono_thread_clr_state (thread, (MonoThreadState)~ThreadState_Background);
405 if (!mono_thread_test_state (thread , ThreadState_Background))
406 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
408 mono_thread_push_appdomain_ref (tpdomain->domain);
409 if (mono_domain_set (tpdomain->domain, FALSE)) {
410 MonoObject *exc = NULL, *res;
412 res = try_invoke_perform_wait_callback (&exc, &error);
413 if (exc || !mono_error_ok(&error)) {
415 exc = (MonoObject *) mono_error_convert_to_exception (&error);
417 mono_error_cleanup (&error);
418 mono_thread_internal_unhandled_exception (exc);
419 } else if (res && *(MonoBoolean*) mono_object_unbox (res) == FALSE) {
423 mono_domain_set (mono_get_root_domain (), TRUE);
425 mono_thread_pop_appdomain_ref ();
429 tpdomain->threadpool_jobs --;
430 g_assert (tpdomain->threadpool_jobs >= 0);
432 if (tpdomain->outstanding_request + tpdomain->threadpool_jobs == 0 && mono_domain_is_unloading (tpdomain->domain)) {
435 removed = tpdomain_remove (tpdomain);
438 mono_coop_cond_signal (&tpdomain->cleanup_cond);
445 previous_tpdomain = tpdomain;
450 mono_coop_mutex_lock (&threadpool.threads_lock);
452 g_ptr_array_remove_fast (threadpool.threads, thread);
454 mono_coop_cond_signal (&threadpool.threads_exit_cond);
456 mono_coop_mutex_unlock (&threadpool.threads_lock);
458 COUNTER_ATOMIC (counter, {
459 counter._.working --;
462 mono_refcount_dec (&threadpool);
466 mono_threadpool_cleanup (void)
468 #ifndef DISABLE_SOCKETS
469 mono_threadpool_io_cleanup ();
471 mono_lazy_cleanup (&status, cleanup);
475 mono_threadpool_begin_invoke (MonoDomain *domain, MonoObject *target, MonoMethod *method, gpointer *params, MonoError *error)
477 static MonoClass *async_call_klass = NULL;
478 MonoMethodMessage *message;
479 MonoAsyncResult *async_result;
480 MonoAsyncCall *async_call;
481 MonoDelegate *async_callback = NULL;
482 MonoObject *state = NULL;
484 if (!async_call_klass)
485 async_call_klass = mono_class_load_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
487 mono_lazy_initialize (&status, initialize);
489 mono_error_init (error);
491 message = mono_method_call_message_new (method, params, mono_get_delegate_invoke (method->klass), (params != NULL) ? (&async_callback) : NULL, (params != NULL) ? (&state) : NULL, error);
492 return_val_if_nok (error, NULL);
494 async_call = (MonoAsyncCall*) mono_object_new_checked (domain, async_call_klass, error);
495 return_val_if_nok (error, NULL);
497 MONO_OBJECT_SETREF (async_call, msg, message);
498 MONO_OBJECT_SETREF (async_call, state, state);
500 if (async_callback) {
501 MONO_OBJECT_SETREF (async_call, cb_method, mono_get_delegate_invoke (((MonoObject*) async_callback)->vtable->klass));
502 MONO_OBJECT_SETREF (async_call, cb_target, async_callback);
505 async_result = mono_async_result_new (domain, NULL, async_call->state, NULL, (MonoObject*) async_call, error);
506 return_val_if_nok (error, NULL);
507 MONO_OBJECT_SETREF (async_result, async_delegate, target);
509 mono_threadpool_enqueue_work_item (domain, (MonoObject*) async_result, error);
510 return_val_if_nok (error, NULL);
516 mono_threadpool_end_invoke (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc, MonoError *error)
520 mono_error_init (error);
527 /* check if already finished */
528 mono_monitor_enter ((MonoObject*) ares);
530 if (ares->endinvoke_called) {
531 mono_error_set_invalid_operation(error, "Delegate EndInvoke method called more than once");
532 mono_monitor_exit ((MonoObject*) ares);
536 ares->endinvoke_called = 1;
538 /* wait until we are really finished */
539 if (ares->completed) {
540 mono_monitor_exit ((MonoObject *) ares);
544 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle*) ares->handle);
546 wait_event = mono_w32event_create (TRUE, FALSE);
547 g_assert(wait_event);
548 MonoWaitHandle *wait_handle = mono_wait_handle_new (mono_object_domain (ares), wait_event, error);
549 if (!is_ok (error)) {
550 mono_w32event_close (wait_event);
553 MONO_OBJECT_SETREF (ares, handle, (MonoObject*) wait_handle);
555 mono_monitor_exit ((MonoObject*) ares);
558 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
560 mono_w32handle_wait_one (wait_event, MONO_INFINITE_WAIT, TRUE);
565 ac = (MonoAsyncCall*) ares->object_data;
568 *exc = ac->msg->exc; /* FIXME: GC add write barrier */
569 *out_args = ac->out_args;
574 mono_threadpool_remove_domain_jobs (MonoDomain *domain, int timeout)
577 ThreadPoolDomain *tpdomain;
581 g_assert (timeout >= -1);
583 g_assert (mono_domain_is_unloading (domain));
586 end = mono_msec_ticks () + timeout;
588 #ifndef DISABLE_SOCKETS
589 mono_threadpool_io_remove_domain_jobs (domain);
591 if (mono_msec_ticks () > end)
597 * Wait for all threads which execute jobs in the domain to exit.
598 * The is_unloading () check in worker_request () ensures that
599 * no new jobs are added after we enter the lock below.
602 if (!mono_lazy_is_initialized (&status))
605 mono_refcount_inc (&threadpool);
609 tpdomain = tpdomain_get (domain);
612 mono_refcount_dec (&threadpool);
618 while (tpdomain->outstanding_request + tpdomain->threadpool_jobs > 0) {
620 mono_coop_cond_wait (&tpdomain->cleanup_cond, &threadpool.domains_lock);
625 now = mono_msec_ticks();
631 res = mono_coop_cond_timedwait (&tpdomain->cleanup_cond, &threadpool.domains_lock, end - now);
639 /* Remove from the list the worker threads look at */
640 tpdomain_remove (tpdomain);
644 mono_coop_cond_destroy (&tpdomain->cleanup_cond);
645 tpdomain_free (tpdomain);
647 mono_refcount_dec (&threadpool);
653 mono_threadpool_suspend (void)
655 if (mono_lazy_is_initialized (&status))
656 mono_threadpool_worker_set_suspended (TRUE);
660 mono_threadpool_resume (void)
662 if (mono_lazy_is_initialized (&status))
663 mono_threadpool_worker_set_suspended (FALSE);
667 ves_icall_System_Threading_ThreadPool_GetAvailableThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
669 ThreadPoolCounter counter;
671 if (!worker_threads || !completion_port_threads)
674 mono_lazy_initialize (&status, initialize);
676 counter = COUNTER_READ ();
678 *worker_threads = MAX (0, mono_threadpool_worker_get_max () - counter._.working);
679 *completion_port_threads = threadpool.limit_io_max;
683 ves_icall_System_Threading_ThreadPool_GetMinThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
685 if (!worker_threads || !completion_port_threads)
688 mono_lazy_initialize (&status, initialize);
690 *worker_threads = mono_threadpool_worker_get_min ();
691 *completion_port_threads = threadpool.limit_io_min;
695 ves_icall_System_Threading_ThreadPool_GetMaxThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
697 if (!worker_threads || !completion_port_threads)
700 mono_lazy_initialize (&status, initialize);
702 *worker_threads = mono_threadpool_worker_get_max ();
703 *completion_port_threads = threadpool.limit_io_max;
707 ves_icall_System_Threading_ThreadPool_SetMinThreadsNative (gint32 worker_threads, gint32 completion_port_threads)
709 mono_lazy_initialize (&status, initialize);
711 if (completion_port_threads <= 0 || completion_port_threads > threadpool.limit_io_max)
714 if (!mono_threadpool_worker_set_min (worker_threads))
717 threadpool.limit_io_min = completion_port_threads;
723 ves_icall_System_Threading_ThreadPool_SetMaxThreadsNative (gint32 worker_threads, gint32 completion_port_threads)
725 gint cpu_count = mono_cpu_count ();
727 mono_lazy_initialize (&status, initialize);
729 if (completion_port_threads < threadpool.limit_io_min || completion_port_threads < cpu_count)
732 if (!mono_threadpool_worker_set_max (worker_threads))
735 threadpool.limit_io_max = completion_port_threads;
741 ves_icall_System_Threading_ThreadPool_InitializeVMTp (MonoBoolean *enable_worker_tracking)
743 if (enable_worker_tracking) {
744 // TODO implement some kind of switch to have the possibily to use it
745 *enable_worker_tracking = FALSE;
748 mono_lazy_initialize (&status, initialize);
752 ves_icall_System_Threading_ThreadPool_NotifyWorkItemComplete (void)
754 if (mono_domain_is_unloading (mono_domain_get ()) || mono_runtime_is_shutting_down ())
757 return mono_threadpool_worker_notify_completed ();
761 ves_icall_System_Threading_ThreadPool_NotifyWorkItemProgressNative (void)
763 mono_threadpool_worker_notify_completed ();
767 ves_icall_System_Threading_ThreadPool_ReportThreadStatus (MonoBoolean is_working)
771 mono_error_set_not_implemented (&error, "");
772 mono_error_set_pending_exception (&error);
776 ves_icall_System_Threading_ThreadPool_RequestWorkerThread (void)
779 ThreadPoolDomain *tpdomain;
780 ThreadPoolCounter counter;
782 domain = mono_domain_get ();
783 if (mono_domain_is_unloading (domain))
786 if (!mono_refcount_tryinc (&threadpool)) {
787 /* threadpool has been destroyed, we are shutting down */
793 tpdomain = tpdomain_get (domain);
795 /* synchronize with mono_threadpool_remove_domain_jobs */
796 if (mono_domain_is_unloading (domain)) {
798 mono_refcount_dec (&threadpool);
802 tpdomain = tpdomain_create (domain);
807 tpdomain->outstanding_request ++;
808 g_assert (tpdomain->outstanding_request >= 1);
812 COUNTER_ATOMIC (counter, {
813 if (counter._.starting == 16) {
814 mono_refcount_dec (&threadpool);
818 counter._.starting ++;
821 mono_threadpool_worker_enqueue (worker_callback, NULL);
823 /* we do not decrement the threadpool refcount,
824 * as it's going to be done in the worker_callback */
829 MonoBoolean G_GNUC_UNUSED
830 ves_icall_System_Threading_ThreadPool_PostQueuedCompletionStatus (MonoNativeOverlapped *native_overlapped)
832 /* This copy the behavior of the current Mono implementation */
834 mono_error_set_not_implemented (&error, "");
835 mono_error_set_pending_exception (&error);
839 MonoBoolean G_GNUC_UNUSED
840 ves_icall_System_Threading_ThreadPool_BindIOCompletionCallbackNative (gpointer file_handle)
842 /* This copy the behavior of the current Mono implementation */
846 MonoBoolean G_GNUC_UNUSED
847 ves_icall_System_Threading_ThreadPool_IsThreadPoolHosted (void)