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;
83 MonoThreadPoolWorker *worker;
86 static mono_lazy_init_t status = MONO_LAZY_INIT_STATUS_NOT_INITIALIZED;
88 static ThreadPool* threadpool;
90 #define COUNTER_CHECK(counter) \
92 g_assert (sizeof (ThreadPoolCounter) == sizeof (gint32)); \
93 g_assert (counter._.starting >= 0); \
94 g_assert (counter._.working >= 0); \
97 #define COUNTER_ATOMIC(threadpool,var,block) \
99 ThreadPoolCounter __old; \
101 g_assert (threadpool); \
102 __old = COUNTER_READ (threadpool); \
105 COUNTER_CHECK (var); \
106 } while (InterlockedCompareExchange (&threadpool->counters.as_gint32, (var).as_gint32, __old.as_gint32) != __old.as_gint32); \
109 static inline ThreadPoolCounter
110 COUNTER_READ (ThreadPool *threadpool)
112 ThreadPoolCounter counter;
113 counter.as_gint32 = InterlockedRead (&threadpool->counters.as_gint32);
120 mono_coop_mutex_lock (&threadpool->domains_lock);
124 domains_unlock (void)
126 mono_coop_mutex_unlock (&threadpool->domains_lock);
130 destroy (gpointer unused)
132 g_ptr_array_free (threadpool->domains, TRUE);
133 mono_coop_mutex_destroy (&threadpool->domains_lock);
135 g_ptr_array_free (threadpool->threads, TRUE);
136 mono_coop_mutex_destroy (&threadpool->threads_lock);
137 mono_coop_cond_destroy (&threadpool->threads_exit_cond);
145 g_assert (!threadpool);
146 threadpool = g_new0 (ThreadPool, 1);
147 g_assert (threadpool);
149 mono_refcount_init (threadpool, destroy);
151 threadpool->domains = g_ptr_array_new ();
152 mono_coop_mutex_init (&threadpool->domains_lock);
154 threadpool->threads = g_ptr_array_new ();
155 mono_coop_mutex_init (&threadpool->threads_lock);
156 mono_coop_cond_init (&threadpool->threads_exit_cond);
158 threadpool->limit_io_min = mono_cpu_count ();
159 threadpool->limit_io_max = CLAMP (threadpool->limit_io_min * 100, MIN (threadpool->limit_io_min, 200), MAX (threadpool->limit_io_min, 200));
161 mono_threadpool_worker_init (&threadpool->worker);
168 MonoInternalThread *current;
170 /* we make the assumption along the code that we are
171 * cleaning up only if the runtime is shutting down */
172 g_assert (mono_runtime_is_shutting_down ());
174 current = mono_thread_internal_current ();
176 mono_coop_mutex_lock (&threadpool->threads_lock);
178 /* stop all threadpool->threads */
179 for (i = 0; i < threadpool->threads->len; ++i) {
180 MonoInternalThread *thread = (MonoInternalThread*) g_ptr_array_index (threadpool->threads, i);
181 if (thread != current)
182 mono_thread_internal_abort (thread);
185 mono_coop_mutex_unlock (&threadpool->threads_lock);
187 /* give a chance to the other threads to exit */
188 mono_thread_info_yield ();
190 mono_coop_mutex_lock (&threadpool->threads_lock);
193 ThreadPoolCounter counter;
195 counter = COUNTER_READ (threadpool);
196 if (counter._.working == 0)
199 if (counter._.working == 1) {
200 if (threadpool->threads->len == 1 && g_ptr_array_index (threadpool->threads, 0) == current) {
201 /* We are waiting on ourselves */
206 mono_coop_cond_wait (&threadpool->threads_exit_cond, &threadpool->threads_lock);
209 mono_coop_mutex_unlock (&threadpool->threads_lock);
211 mono_threadpool_worker_cleanup (threadpool->worker);
213 mono_refcount_dec (threadpool);
217 mono_threadpool_enqueue_work_item (MonoDomain *domain, MonoObject *work_item, MonoError *error)
219 static MonoClass *threadpool_class = NULL;
220 static MonoMethod *unsafe_queue_custom_work_item_method = NULL;
221 MonoDomain *current_domain;
225 mono_error_init (error);
226 g_assert (work_item);
228 if (!threadpool_class)
229 threadpool_class = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "ThreadPool");
231 if (!unsafe_queue_custom_work_item_method)
232 unsafe_queue_custom_work_item_method = mono_class_get_method_from_name (threadpool_class, "UnsafeQueueCustomWorkItem", 2);
233 g_assert (unsafe_queue_custom_work_item_method);
237 args [0] = (gpointer) work_item;
238 args [1] = (gpointer) &f;
240 current_domain = mono_domain_get ();
241 if (current_domain == domain) {
242 mono_runtime_invoke_checked (unsafe_queue_custom_work_item_method, NULL, args, error);
243 return_val_if_nok (error, FALSE);
245 mono_thread_push_appdomain_ref (domain);
246 if (mono_domain_set (domain, FALSE)) {
247 mono_runtime_invoke_checked (unsafe_queue_custom_work_item_method, NULL, args, error);
248 if (!is_ok (error)) {
249 mono_thread_pop_appdomain_ref ();
252 mono_domain_set (current_domain, TRUE);
254 mono_thread_pop_appdomain_ref ();
259 /* LOCKING: domains_lock must be held */
261 tpdomain_add (ThreadPoolDomain *tpdomain)
267 len = threadpool->domains->len;
268 for (i = 0; i < len; ++i) {
269 if (g_ptr_array_index (threadpool->domains, i) == tpdomain)
274 g_ptr_array_add (threadpool->domains, tpdomain);
277 /* LOCKING: domains_lock must be held. */
279 tpdomain_remove (ThreadPoolDomain *tpdomain)
282 return g_ptr_array_remove (threadpool->domains, tpdomain);
285 /* LOCKING: domains_lock must be held */
286 static ThreadPoolDomain *
287 tpdomain_get (MonoDomain *domain, gboolean create)
290 ThreadPoolDomain *tpdomain;
294 for (i = 0; i < threadpool->domains->len; ++i) {
295 ThreadPoolDomain *tpdomain;
297 tpdomain = (ThreadPoolDomain *)g_ptr_array_index (threadpool->domains, i);
298 if (tpdomain->domain == domain)
305 tpdomain = g_new0 (ThreadPoolDomain, 1);
306 tpdomain->domain = domain;
307 mono_coop_cond_init (&tpdomain->cleanup_cond);
309 tpdomain_add (tpdomain);
315 tpdomain_free (ThreadPoolDomain *tpdomain)
320 /* LOCKING: domains_lock must be held */
321 static ThreadPoolDomain *
322 tpdomain_get_next (ThreadPoolDomain *current)
324 ThreadPoolDomain *tpdomain = NULL;
327 len = threadpool->domains->len;
329 guint i, current_idx = -1;
331 for (i = 0; i < len; ++i) {
332 if (current == g_ptr_array_index (threadpool->domains, i)) {
337 g_assert (current_idx != (guint)-1);
339 for (i = current_idx + 1; i < len + current_idx + 1; ++i) {
340 ThreadPoolDomain *tmp = (ThreadPoolDomain *)g_ptr_array_index (threadpool->domains, i % len);
341 if (tmp->outstanding_request > 0) {
352 worker_callback (gpointer unused)
355 ThreadPoolDomain *tpdomain, *previous_tpdomain;
356 ThreadPoolCounter counter;
357 MonoInternalThread *thread;
359 thread = mono_thread_internal_current ();
361 COUNTER_ATOMIC (threadpool, counter, {
362 counter._.starting --;
363 counter._.working ++;
366 if (mono_runtime_is_shutting_down ()) {
367 COUNTER_ATOMIC (threadpool, counter, {
368 counter._.working --;
371 mono_refcount_dec (threadpool);
375 mono_coop_mutex_lock (&threadpool->threads_lock);
376 g_ptr_array_add (threadpool->threads, thread);
377 mono_coop_mutex_unlock (&threadpool->threads_lock);
380 * This is needed so there is always an lmf frame in the runtime invoke call below,
381 * so ThreadAbortExceptions are caught even if the thread is in native code.
383 mono_defaults.threadpool_perform_wait_callback_method->save_lmf = TRUE;
387 previous_tpdomain = NULL;
389 while (!mono_runtime_is_shutting_down ()) {
390 gboolean retire = FALSE;
392 if ((thread->state & (ThreadState_AbortRequested | ThreadState_SuspendRequested)) != 0) {
394 mono_thread_interruption_checkpoint ();
398 tpdomain = tpdomain_get_next (previous_tpdomain);
402 tpdomain->outstanding_request --;
403 g_assert (tpdomain->outstanding_request >= 0);
405 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] worker running in domain %p (outstanding requests %d)",
406 mono_native_thread_id_get (), tpdomain->domain, tpdomain->outstanding_request);
408 g_assert (tpdomain->threadpool_jobs >= 0);
409 tpdomain->threadpool_jobs ++;
413 mono_thread_clr_state (thread, (MonoThreadState)~ThreadState_Background);
414 if (!mono_thread_test_state (thread , ThreadState_Background))
415 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
417 mono_thread_push_appdomain_ref (tpdomain->domain);
418 if (mono_domain_set (tpdomain->domain, FALSE)) {
419 MonoObject *exc = NULL, *res;
421 res = mono_runtime_try_invoke (mono_defaults.threadpool_perform_wait_callback_method, NULL, NULL, &exc, &error);
422 if (exc || !mono_error_ok(&error)) {
424 exc = (MonoObject *) mono_error_convert_to_exception (&error);
426 mono_error_cleanup (&error);
427 mono_thread_internal_unhandled_exception (exc);
428 } else if (res && *(MonoBoolean*) mono_object_unbox (res) == FALSE) {
432 mono_domain_set (mono_get_root_domain (), TRUE);
434 mono_thread_pop_appdomain_ref ();
438 tpdomain->threadpool_jobs --;
439 g_assert (tpdomain->threadpool_jobs >= 0);
441 if (tpdomain->outstanding_request + tpdomain->threadpool_jobs == 0 && mono_domain_is_unloading (tpdomain->domain)) {
444 removed = tpdomain_remove (tpdomain);
447 mono_coop_cond_signal (&tpdomain->cleanup_cond);
454 previous_tpdomain = tpdomain;
459 mono_coop_mutex_lock (&threadpool->threads_lock);
461 COUNTER_ATOMIC (threadpool, counter, {
462 counter._.working --;
465 g_ptr_array_remove_fast (threadpool->threads, thread);
467 mono_coop_cond_signal (&threadpool->threads_exit_cond);
469 mono_coop_mutex_unlock (&threadpool->threads_lock);
471 mono_refcount_dec (threadpool);
475 mono_threadpool_cleanup (void)
477 #ifndef DISABLE_SOCKETS
478 mono_threadpool_io_cleanup ();
480 mono_lazy_cleanup (&status, cleanup);
484 mono_threadpool_begin_invoke (MonoDomain *domain, MonoObject *target, MonoMethod *method, gpointer *params, MonoError *error)
486 static MonoClass *async_call_klass = NULL;
487 MonoMethodMessage *message;
488 MonoAsyncResult *async_result;
489 MonoAsyncCall *async_call;
490 MonoDelegate *async_callback = NULL;
491 MonoObject *state = NULL;
493 if (!async_call_klass)
494 async_call_klass = mono_class_load_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
496 mono_lazy_initialize (&status, initialize);
498 mono_error_init (error);
500 message = mono_method_call_message_new (method, params, mono_get_delegate_invoke (method->klass), (params != NULL) ? (&async_callback) : NULL, (params != NULL) ? (&state) : NULL, error);
501 return_val_if_nok (error, NULL);
503 async_call = (MonoAsyncCall*) mono_object_new_checked (domain, async_call_klass, error);
504 return_val_if_nok (error, NULL);
506 MONO_OBJECT_SETREF (async_call, msg, message);
507 MONO_OBJECT_SETREF (async_call, state, state);
509 if (async_callback) {
510 MONO_OBJECT_SETREF (async_call, cb_method, mono_get_delegate_invoke (((MonoObject*) async_callback)->vtable->klass));
511 MONO_OBJECT_SETREF (async_call, cb_target, async_callback);
514 async_result = mono_async_result_new (domain, NULL, async_call->state, NULL, (MonoObject*) async_call, error);
515 return_val_if_nok (error, NULL);
516 MONO_OBJECT_SETREF (async_result, async_delegate, target);
518 mono_threadpool_enqueue_work_item (domain, (MonoObject*) async_result, error);
519 return_val_if_nok (error, NULL);
525 mono_threadpool_end_invoke (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc, MonoError *error)
529 mono_error_init (error);
536 /* check if already finished */
537 mono_monitor_enter ((MonoObject*) ares);
539 if (ares->endinvoke_called) {
540 mono_error_set_invalid_operation(error, "Delegate EndInvoke method called more than once");
541 mono_monitor_exit ((MonoObject*) ares);
545 ares->endinvoke_called = 1;
547 /* wait until we are really finished */
548 if (ares->completed) {
549 mono_monitor_exit ((MonoObject *) ares);
553 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle*) ares->handle);
555 wait_event = mono_w32event_create (TRUE, FALSE);
556 g_assert(wait_event);
557 MonoWaitHandle *wait_handle = mono_wait_handle_new (mono_object_domain (ares), wait_event, error);
558 if (!is_ok (error)) {
559 CloseHandle (wait_event);
562 MONO_OBJECT_SETREF (ares, handle, (MonoObject*) wait_handle);
564 mono_monitor_exit ((MonoObject*) ares);
567 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
569 mono_w32handle_wait_one (wait_event, MONO_INFINITE_WAIT, TRUE);
574 ac = (MonoAsyncCall*) ares->object_data;
577 *exc = ac->msg->exc; /* FIXME: GC add write barrier */
578 *out_args = ac->out_args;
583 mono_threadpool_remove_domain_jobs (MonoDomain *domain, int timeout)
586 ThreadPoolDomain *tpdomain;
590 g_assert (timeout >= -1);
592 g_assert (mono_domain_is_unloading (domain));
595 end = mono_msec_ticks () + timeout;
597 #ifndef DISABLE_SOCKETS
598 mono_threadpool_io_remove_domain_jobs (domain);
600 if (mono_msec_ticks () > end)
606 * Wait for all threads which execute jobs in the domain to exit.
607 * The is_unloading () check in worker_request () ensures that
608 * no new jobs are added after we enter the lock below.
610 mono_lazy_initialize (&status, initialize);
613 tpdomain = tpdomain_get (domain, FALSE);
621 while (tpdomain->outstanding_request + tpdomain->threadpool_jobs > 0) {
623 mono_coop_cond_wait (&tpdomain->cleanup_cond, &threadpool->domains_lock);
628 now = mono_msec_ticks();
634 res = mono_coop_cond_timedwait (&tpdomain->cleanup_cond, &threadpool->domains_lock, end - now);
642 /* Remove from the list the worker threads look at */
643 tpdomain_remove (tpdomain);
647 mono_coop_cond_destroy (&tpdomain->cleanup_cond);
648 tpdomain_free (tpdomain);
654 mono_threadpool_suspend (void)
657 mono_threadpool_worker_set_suspended (threadpool->worker, TRUE);
661 mono_threadpool_resume (void)
664 mono_threadpool_worker_set_suspended (threadpool->worker, FALSE);
668 ves_icall_System_Threading_ThreadPool_GetAvailableThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
670 ThreadPoolCounter counter;
672 if (!worker_threads || !completion_port_threads)
675 mono_lazy_initialize (&status, initialize);
677 counter = COUNTER_READ (threadpool);
679 *worker_threads = MAX (0, mono_threadpool_worker_get_max (threadpool->worker) - counter._.working);
680 *completion_port_threads = threadpool->limit_io_max;
684 ves_icall_System_Threading_ThreadPool_GetMinThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
686 if (!worker_threads || !completion_port_threads)
689 mono_lazy_initialize (&status, initialize);
691 *worker_threads = mono_threadpool_worker_get_min (threadpool->worker);
692 *completion_port_threads = threadpool->limit_io_min;
696 ves_icall_System_Threading_ThreadPool_GetMaxThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
698 if (!worker_threads || !completion_port_threads)
701 mono_lazy_initialize (&status, initialize);
703 *worker_threads = mono_threadpool_worker_get_max (threadpool->worker);
704 *completion_port_threads = threadpool->limit_io_max;
708 ves_icall_System_Threading_ThreadPool_SetMinThreadsNative (gint32 worker_threads, gint32 completion_port_threads)
710 mono_lazy_initialize (&status, initialize);
712 if (completion_port_threads <= 0 || completion_port_threads > threadpool->limit_io_max)
715 if (!mono_threadpool_worker_set_min (threadpool->worker, worker_threads))
718 threadpool->limit_io_min = completion_port_threads;
724 ves_icall_System_Threading_ThreadPool_SetMaxThreadsNative (gint32 worker_threads, gint32 completion_port_threads)
726 gint cpu_count = mono_cpu_count ();
728 mono_lazy_initialize (&status, initialize);
730 if (completion_port_threads < threadpool->limit_io_min || completion_port_threads < cpu_count)
733 if (!mono_threadpool_worker_set_max (threadpool->worker, worker_threads))
736 threadpool->limit_io_max = completion_port_threads;
742 ves_icall_System_Threading_ThreadPool_InitializeVMTp (MonoBoolean *enable_worker_tracking)
744 if (enable_worker_tracking) {
745 // TODO implement some kind of switch to have the possibily to use it
746 *enable_worker_tracking = FALSE;
749 mono_lazy_initialize (&status, initialize);
753 ves_icall_System_Threading_ThreadPool_NotifyWorkItemComplete (void)
755 if (mono_domain_is_unloading (mono_domain_get ()) || mono_runtime_is_shutting_down ())
758 return mono_threadpool_worker_notify_completed (threadpool->worker);
762 ves_icall_System_Threading_ThreadPool_NotifyWorkItemProgressNative (void)
764 mono_threadpool_worker_notify_completed (threadpool->worker);
768 ves_icall_System_Threading_ThreadPool_ReportThreadStatus (MonoBoolean is_working)
772 mono_error_set_not_implemented (&error, "");
773 mono_error_set_pending_exception (&error);
777 ves_icall_System_Threading_ThreadPool_RequestWorkerThread (void)
780 ThreadPoolDomain *tpdomain;
781 ThreadPoolCounter counter;
783 domain = mono_domain_get ();
784 if (mono_domain_is_unloading (domain))
789 /* synchronize with mono_threadpool_remove_domain_jobs */
790 if (mono_domain_is_unloading (domain)) {
795 tpdomain = tpdomain_get (domain, TRUE);
798 tpdomain->outstanding_request ++;
799 g_assert (tpdomain->outstanding_request >= 1);
801 mono_refcount_inc (threadpool);
803 COUNTER_ATOMIC (threadpool, counter, {
804 counter._.starting ++;
807 mono_threadpool_worker_enqueue (threadpool->worker, worker_callback, NULL);
814 MonoBoolean G_GNUC_UNUSED
815 ves_icall_System_Threading_ThreadPool_PostQueuedCompletionStatus (MonoNativeOverlapped *native_overlapped)
817 /* This copy the behavior of the current Mono implementation */
819 mono_error_set_not_implemented (&error, "");
820 mono_error_set_pending_exception (&error);
824 MonoBoolean G_GNUC_UNUSED
825 ves_icall_System_Threading_ThreadPool_BindIOCompletionCallbackNative (gpointer file_handle)
827 /* This copy the behavior of the current Mono implementation */
831 MonoBoolean G_GNUC_UNUSED
832 ves_icall_System_Threading_ThreadPool_IsThreadPoolHosted (void)