3 * Microsoft threadpool runtime support
6 * Ludovic Henry (ludovic.henry@xamarin.com)
8 * Copyright 2015 Xamarin, Inc (http://www.xamarin.com)
9 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
13 // Copyright (c) Microsoft. All rights reserved.
14 // Licensed under the MIT license. See LICENSE file in the project root for full license information.
17 // - src/vm/comthreadpool.cpp
18 // - src/vm/win32threadpoolcpp
19 // - src/vm/threadpoolrequest.cpp
20 // - src/vm/hillclimbing.cpp
22 // Ported from C++ to C and adjusted to Mono runtime
25 #define _USE_MATH_DEFINES // needed by MSVC to define math constants
30 #include <mono/metadata/class-internals.h>
31 #include <mono/metadata/exception.h>
32 #include <mono/metadata/gc-internals.h>
33 #include <mono/metadata/object.h>
34 #include <mono/metadata/object-internals.h>
35 #include <mono/metadata/threadpool.h>
36 #include <mono/metadata/threadpool-worker.h>
37 #include <mono/metadata/threadpool-io.h>
38 #include <mono/metadata/w32event.h>
39 #include <mono/utils/atomic.h>
40 #include <mono/utils/mono-compiler.h>
41 #include <mono/utils/mono-complex.h>
42 #include <mono/utils/mono-lazy-init.h>
43 #include <mono/utils/mono-logger.h>
44 #include <mono/utils/mono-logger-internals.h>
45 #include <mono/utils/mono-proclib.h>
46 #include <mono/utils/mono-threads.h>
47 #include <mono/utils/mono-time.h>
48 #include <mono/utils/refcount.h>
52 /* Number of outstanding jobs */
53 gint32 outstanding_request;
54 /* Number of currently executing jobs */
55 gint32 threadpool_jobs;
56 /* Signalled when threadpool_jobs + outstanding_request is 0 */
57 /* Protected by threadpool.domains_lock */
58 MonoCoopCond cleanup_cond;
63 gint16 starting; /* starting, but not yet in worker_callback */
64 gint16 working; /* executing worker_callback */
72 GPtrArray *domains; // ThreadPoolDomain* []
73 MonoCoopMutex domains_lock;
75 ThreadPoolCounter counters;
81 static mono_lazy_init_t status = MONO_LAZY_INIT_STATUS_NOT_INITIALIZED;
83 static ThreadPool threadpool;
85 #define COUNTER_ATOMIC(var,block) \
87 ThreadPoolCounter __old; \
89 (var) = __old = COUNTER_READ (); \
91 if (!(counter._.starting >= 0)) \
92 g_error ("%s: counter._.starting = %d, but should be >= 0", __func__, counter._.starting); \
93 if (!(counter._.working >= 0)) \
94 g_error ("%s: counter._.working = %d, but should be >= 0", __func__, counter._.working); \
95 } while (InterlockedCompareExchange (&threadpool.counters.as_gint32, (var).as_gint32, __old.as_gint32) != __old.as_gint32); \
98 static inline ThreadPoolCounter
101 ThreadPoolCounter counter;
102 counter.as_gint32 = InterlockedRead (&threadpool.counters.as_gint32);
109 mono_coop_mutex_lock (&threadpool.domains_lock);
113 domains_unlock (void)
115 mono_coop_mutex_unlock (&threadpool.domains_lock);
119 destroy (gpointer unused)
121 g_ptr_array_free (threadpool.domains, TRUE);
122 mono_coop_mutex_destroy (&threadpool.domains_lock);
126 worker_callback (void);
131 g_assert (sizeof (ThreadPoolCounter) == sizeof (gint32));
133 mono_refcount_init (&threadpool, destroy);
135 threadpool.domains = g_ptr_array_new ();
136 mono_coop_mutex_init (&threadpool.domains_lock);
138 threadpool.limit_io_min = mono_cpu_count ();
139 threadpool.limit_io_max = CLAMP (threadpool.limit_io_min * 100, MIN (threadpool.limit_io_min, 200), MAX (threadpool.limit_io_min, 200));
141 mono_threadpool_worker_init (worker_callback);
147 mono_threadpool_worker_cleanup ();
149 mono_refcount_dec (&threadpool);
153 mono_threadpool_enqueue_work_item (MonoDomain *domain, MonoObject *work_item, MonoError *error)
155 static MonoClass *threadpool_class = NULL;
156 static MonoMethod *unsafe_queue_custom_work_item_method = NULL;
157 MonoDomain *current_domain;
162 g_assert (work_item);
164 if (!threadpool_class)
165 threadpool_class = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "ThreadPool");
167 if (!unsafe_queue_custom_work_item_method)
168 unsafe_queue_custom_work_item_method = mono_class_get_method_from_name (threadpool_class, "UnsafeQueueCustomWorkItem", 2);
169 g_assert (unsafe_queue_custom_work_item_method);
173 args [0] = (gpointer) work_item;
174 args [1] = (gpointer) &f;
176 current_domain = mono_domain_get ();
177 if (current_domain == domain) {
178 mono_runtime_invoke_checked (unsafe_queue_custom_work_item_method, NULL, args, error);
179 return_val_if_nok (error, FALSE);
181 mono_thread_push_appdomain_ref (domain);
182 if (mono_domain_set (domain, FALSE)) {
183 mono_runtime_invoke_checked (unsafe_queue_custom_work_item_method, NULL, args, error);
184 if (!is_ok (error)) {
185 mono_thread_pop_appdomain_ref ();
188 mono_domain_set (current_domain, TRUE);
190 mono_thread_pop_appdomain_ref ();
195 /* LOCKING: domains_lock must be held. */
196 static ThreadPoolDomain *
197 tpdomain_create (MonoDomain *domain)
199 ThreadPoolDomain *tpdomain;
201 tpdomain = g_new0 (ThreadPoolDomain, 1);
202 tpdomain->domain = domain;
203 mono_coop_cond_init (&tpdomain->cleanup_cond);
205 g_ptr_array_add (threadpool.domains, tpdomain);
210 /* LOCKING: domains_lock must be held. */
212 tpdomain_remove (ThreadPoolDomain *tpdomain)
215 return g_ptr_array_remove (threadpool.domains, tpdomain);
218 /* LOCKING: domains_lock must be held */
219 static ThreadPoolDomain *
220 tpdomain_get (MonoDomain *domain)
226 for (i = 0; i < threadpool.domains->len; ++i) {
227 ThreadPoolDomain *tpdomain;
229 tpdomain = (ThreadPoolDomain *)g_ptr_array_index (threadpool.domains, i);
230 if (tpdomain->domain == domain)
238 tpdomain_free (ThreadPoolDomain *tpdomain)
243 /* LOCKING: domains_lock must be held */
244 static ThreadPoolDomain *
245 tpdomain_get_next (ThreadPoolDomain *current)
247 ThreadPoolDomain *tpdomain = NULL;
250 len = threadpool.domains->len;
252 gint i, current_idx = -1;
254 for (i = 0; i < len; ++i) {
255 if (current == g_ptr_array_index (threadpool.domains, i)) {
261 for (i = current_idx + 1; i < len + current_idx + 1; ++i) {
262 ThreadPoolDomain *tmp = (ThreadPoolDomain *)g_ptr_array_index (threadpool.domains, i % len);
263 if (tmp->outstanding_request > 0) {
274 try_invoke_perform_wait_callback (MonoObject** exc, MonoError *error)
276 HANDLE_FUNCTION_ENTER ();
278 MonoObject *res = mono_runtime_try_invoke (mono_defaults.threadpool_perform_wait_callback_method, NULL, NULL, exc, error);
279 HANDLE_FUNCTION_RETURN_VAL (res);
283 worker_callback (void)
286 ThreadPoolDomain *tpdomain, *previous_tpdomain;
287 ThreadPoolCounter counter;
288 MonoInternalThread *thread;
290 if (!mono_refcount_tryinc (&threadpool))
293 thread = mono_thread_internal_current ();
295 COUNTER_ATOMIC (counter, {
296 if (!(counter._.working < 32767 /* G_MAXINT16 */))
297 g_error ("%s: counter._.working = %d, but should be < 32767", __func__, counter._.working);
299 counter._.starting --;
300 counter._.working ++;
303 if (mono_runtime_is_shutting_down ()) {
304 COUNTER_ATOMIC (counter, {
305 counter._.working --;
308 mono_refcount_dec (&threadpool);
313 * This is needed so there is always an lmf frame in the runtime invoke call below,
314 * so ThreadAbortExceptions are caught even if the thread is in native code.
316 mono_defaults.threadpool_perform_wait_callback_method->save_lmf = TRUE;
320 previous_tpdomain = NULL;
322 while (!mono_runtime_is_shutting_down ()) {
323 gboolean retire = FALSE;
325 if (thread->state & (ThreadState_AbortRequested | ThreadState_SuspendRequested)) {
327 if (mono_thread_interruption_checkpoint ()) {
334 tpdomain = tpdomain_get_next (previous_tpdomain);
338 tpdomain->outstanding_request --;
339 g_assert (tpdomain->outstanding_request >= 0);
341 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] worker running in domain %p (outstanding requests %d)",
342 mono_native_thread_id_get (), tpdomain->domain, tpdomain->outstanding_request);
344 g_assert (tpdomain->threadpool_jobs >= 0);
345 tpdomain->threadpool_jobs ++;
349 mono_thread_set_name_internal (thread, mono_string_new (mono_get_root_domain (), "Threadpool worker"), FALSE, TRUE, &error);
350 mono_error_assert_ok (&error);
352 mono_thread_clr_state (thread, (MonoThreadState)~ThreadState_Background);
353 if (!mono_thread_test_state (thread , ThreadState_Background))
354 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
356 mono_thread_push_appdomain_ref (tpdomain->domain);
357 if (mono_domain_set (tpdomain->domain, FALSE)) {
358 MonoObject *exc = NULL, *res;
360 res = try_invoke_perform_wait_callback (&exc, &error);
361 if (exc || !mono_error_ok(&error)) {
363 exc = (MonoObject *) mono_error_convert_to_exception (&error);
365 mono_error_cleanup (&error);
366 mono_thread_internal_unhandled_exception (exc);
367 } else if (res && *(MonoBoolean*) mono_object_unbox (res) == FALSE) {
371 mono_domain_set (mono_get_root_domain (), TRUE);
373 mono_thread_pop_appdomain_ref ();
377 tpdomain->threadpool_jobs --;
378 g_assert (tpdomain->threadpool_jobs >= 0);
380 if (tpdomain->outstanding_request + tpdomain->threadpool_jobs == 0 && mono_domain_is_unloading (tpdomain->domain)) {
383 removed = tpdomain_remove (tpdomain);
386 mono_coop_cond_signal (&tpdomain->cleanup_cond);
393 previous_tpdomain = tpdomain;
398 COUNTER_ATOMIC (counter, {
399 counter._.working --;
402 mono_refcount_dec (&threadpool);
406 mono_threadpool_cleanup (void)
408 #ifndef DISABLE_SOCKETS
409 mono_threadpool_io_cleanup ();
411 mono_lazy_cleanup (&status, cleanup);
415 mono_threadpool_begin_invoke (MonoDomain *domain, MonoObject *target, MonoMethod *method, gpointer *params, MonoError *error)
417 static MonoClass *async_call_klass = NULL;
418 MonoMethodMessage *message;
419 MonoAsyncResult *async_result;
420 MonoAsyncCall *async_call;
421 MonoDelegate *async_callback = NULL;
422 MonoObject *state = NULL;
424 if (!async_call_klass)
425 async_call_klass = mono_class_load_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
429 message = mono_method_call_message_new (method, params, mono_get_delegate_invoke (method->klass), (params != NULL) ? (&async_callback) : NULL, (params != NULL) ? (&state) : NULL, error);
430 return_val_if_nok (error, NULL);
432 async_call = (MonoAsyncCall*) mono_object_new_checked (domain, async_call_klass, error);
433 return_val_if_nok (error, NULL);
435 MONO_OBJECT_SETREF (async_call, msg, message);
436 MONO_OBJECT_SETREF (async_call, state, state);
438 if (async_callback) {
439 MONO_OBJECT_SETREF (async_call, cb_method, mono_get_delegate_invoke (((MonoObject*) async_callback)->vtable->klass));
440 MONO_OBJECT_SETREF (async_call, cb_target, async_callback);
443 async_result = mono_async_result_new (domain, NULL, async_call->state, NULL, (MonoObject*) async_call, error);
444 return_val_if_nok (error, NULL);
445 MONO_OBJECT_SETREF (async_result, async_delegate, target);
447 mono_threadpool_enqueue_work_item (domain, (MonoObject*) async_result, error);
448 return_val_if_nok (error, NULL);
454 mono_threadpool_end_invoke (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc, MonoError *error)
465 /* check if already finished */
466 mono_monitor_enter ((MonoObject*) ares);
468 if (ares->endinvoke_called) {
469 mono_error_set_invalid_operation(error, "Delegate EndInvoke method called more than once");
470 mono_monitor_exit ((MonoObject*) ares);
474 ares->endinvoke_called = 1;
476 /* wait until we are really finished */
477 if (ares->completed) {
478 mono_monitor_exit ((MonoObject *) ares);
482 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle*) ares->handle);
484 wait_event = mono_w32event_create (TRUE, FALSE);
485 g_assert(wait_event);
486 MonoWaitHandle *wait_handle = mono_wait_handle_new (mono_object_domain (ares), wait_event, error);
487 if (!is_ok (error)) {
488 mono_w32event_close (wait_event);
491 MONO_OBJECT_SETREF (ares, handle, (MonoObject*) wait_handle);
493 mono_monitor_exit ((MonoObject*) ares);
496 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
498 mono_w32handle_wait_one (wait_event, MONO_INFINITE_WAIT, TRUE);
503 ac = (MonoAsyncCall*) ares->object_data;
506 *exc = ac->msg->exc; /* FIXME: GC add write barrier */
507 *out_args = ac->out_args;
512 mono_threadpool_remove_domain_jobs (MonoDomain *domain, int timeout)
515 ThreadPoolDomain *tpdomain;
519 g_assert (timeout >= -1);
521 g_assert (mono_domain_is_unloading (domain));
524 end = mono_msec_ticks () + timeout;
526 #ifndef DISABLE_SOCKETS
527 mono_threadpool_io_remove_domain_jobs (domain);
529 if (mono_msec_ticks () > end)
535 * Wait for all threads which execute jobs in the domain to exit.
536 * The is_unloading () check in worker_request () ensures that
537 * no new jobs are added after we enter the lock below.
540 if (!mono_lazy_is_initialized (&status))
543 mono_refcount_inc (&threadpool);
547 tpdomain = tpdomain_get (domain);
550 mono_refcount_dec (&threadpool);
556 while (tpdomain->outstanding_request + tpdomain->threadpool_jobs > 0) {
558 mono_coop_cond_wait (&tpdomain->cleanup_cond, &threadpool.domains_lock);
563 now = mono_msec_ticks();
569 res = mono_coop_cond_timedwait (&tpdomain->cleanup_cond, &threadpool.domains_lock, end - now);
577 /* Remove from the list the worker threads look at */
578 tpdomain_remove (tpdomain);
582 mono_coop_cond_destroy (&tpdomain->cleanup_cond);
583 tpdomain_free (tpdomain);
585 mono_refcount_dec (&threadpool);
591 mono_threadpool_suspend (void)
593 if (mono_lazy_is_initialized (&status))
594 mono_threadpool_worker_set_suspended (TRUE);
598 mono_threadpool_resume (void)
600 if (mono_lazy_is_initialized (&status))
601 mono_threadpool_worker_set_suspended (FALSE);
605 ves_icall_System_Threading_ThreadPool_GetAvailableThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
607 ThreadPoolCounter counter;
609 if (!worker_threads || !completion_port_threads)
612 if (!mono_lazy_initialize (&status, initialize) || !mono_refcount_tryinc (&threadpool)) {
614 *completion_port_threads = 0;
618 counter = COUNTER_READ ();
620 *worker_threads = MAX (0, mono_threadpool_worker_get_max () - counter._.working);
621 *completion_port_threads = threadpool.limit_io_max;
623 mono_refcount_dec (&threadpool);
627 ves_icall_System_Threading_ThreadPool_GetMinThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
629 if (!worker_threads || !completion_port_threads)
632 if (!mono_lazy_initialize (&status, initialize) || !mono_refcount_tryinc (&threadpool)) {
634 *completion_port_threads = 0;
638 *worker_threads = mono_threadpool_worker_get_min ();
639 *completion_port_threads = threadpool.limit_io_min;
641 mono_refcount_dec (&threadpool);
645 ves_icall_System_Threading_ThreadPool_GetMaxThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
647 if (!worker_threads || !completion_port_threads)
650 if (!mono_lazy_initialize (&status, initialize) || !mono_refcount_tryinc (&threadpool)) {
652 *completion_port_threads = 0;
656 *worker_threads = mono_threadpool_worker_get_max ();
657 *completion_port_threads = threadpool.limit_io_max;
659 mono_refcount_dec (&threadpool);
663 ves_icall_System_Threading_ThreadPool_SetMinThreadsNative (gint32 worker_threads, gint32 completion_port_threads)
665 if (completion_port_threads <= 0 || completion_port_threads > threadpool.limit_io_max)
668 if (!mono_lazy_initialize (&status, initialize) || !mono_refcount_tryinc (&threadpool))
671 if (!mono_threadpool_worker_set_min (worker_threads)) {
672 mono_refcount_dec (&threadpool);
676 threadpool.limit_io_min = completion_port_threads;
678 mono_refcount_dec (&threadpool);
683 ves_icall_System_Threading_ThreadPool_SetMaxThreadsNative (gint32 worker_threads, gint32 completion_port_threads)
685 gint cpu_count = mono_cpu_count ();
687 if (completion_port_threads < threadpool.limit_io_min || completion_port_threads < cpu_count)
690 if (!mono_lazy_initialize (&status, initialize) || !mono_refcount_tryinc (&threadpool))
693 if (!mono_threadpool_worker_set_max (worker_threads)) {
694 mono_refcount_dec (&threadpool);
698 threadpool.limit_io_max = completion_port_threads;
700 mono_refcount_dec (&threadpool);
705 ves_icall_System_Threading_ThreadPool_InitializeVMTp (MonoBoolean *enable_worker_tracking)
707 if (enable_worker_tracking) {
708 // TODO implement some kind of switch to have the possibily to use it
709 *enable_worker_tracking = FALSE;
712 mono_lazy_initialize (&status, initialize);
716 ves_icall_System_Threading_ThreadPool_NotifyWorkItemComplete (void)
718 if (mono_domain_is_unloading (mono_domain_get ()) || mono_runtime_is_shutting_down ())
721 return mono_threadpool_worker_notify_completed ();
725 ves_icall_System_Threading_ThreadPool_NotifyWorkItemProgressNative (void)
727 mono_threadpool_worker_notify_completed ();
731 ves_icall_System_Threading_ThreadPool_ReportThreadStatus (MonoBoolean is_working)
735 mono_error_set_not_implemented (&error, "");
736 mono_error_set_pending_exception (&error);
740 ves_icall_System_Threading_ThreadPool_RequestWorkerThread (void)
743 ThreadPoolDomain *tpdomain;
744 ThreadPoolCounter counter;
746 domain = mono_domain_get ();
747 if (mono_domain_is_unloading (domain))
750 if (!mono_lazy_initialize (&status, initialize) || !mono_refcount_tryinc (&threadpool)) {
751 /* threadpool has been destroyed, we are shutting down */
757 tpdomain = tpdomain_get (domain);
759 /* synchronize with mono_threadpool_remove_domain_jobs */
760 if (mono_domain_is_unloading (domain)) {
762 mono_refcount_dec (&threadpool);
766 tpdomain = tpdomain_create (domain);
771 tpdomain->outstanding_request ++;
772 g_assert (tpdomain->outstanding_request >= 1);
776 COUNTER_ATOMIC (counter, {
777 if (counter._.starting == 16) {
778 mono_refcount_dec (&threadpool);
782 counter._.starting ++;
785 mono_threadpool_worker_request ();
787 mono_refcount_dec (&threadpool);
791 MonoBoolean G_GNUC_UNUSED
792 ves_icall_System_Threading_ThreadPool_PostQueuedCompletionStatus (MonoNativeOverlapped *native_overlapped)
794 /* This copy the behavior of the current Mono implementation */
796 mono_error_set_not_implemented (&error, "");
797 mono_error_set_pending_exception (&error);
801 MonoBoolean G_GNUC_UNUSED
802 ves_icall_System_Threading_ThreadPool_BindIOCompletionCallbackNative (gpointer file_handle)
804 /* This copy the behavior of the current Mono implementation */
808 MonoBoolean G_GNUC_UNUSED
809 ves_icall_System_Threading_ThreadPool_IsThreadPoolHosted (void)