2 * threadpool-ms.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-ms.h>
35 #include <mono/metadata/threadpool-ms-io.h>
36 #include <mono/metadata/w32event.h>
37 #include <mono/utils/atomic.h>
38 #include <mono/utils/mono-compiler.h>
39 #include <mono/utils/mono-complex.h>
40 #include <mono/utils/mono-lazy-init.h>
41 #include <mono/utils/mono-logger.h>
42 #include <mono/utils/mono-logger-internals.h>
43 #include <mono/utils/mono-proclib.h>
44 #include <mono/utils/mono-threads.h>
45 #include <mono/utils/mono-time.h>
46 #include <mono/utils/mono-rand.h>
48 #define CPU_USAGE_LOW 80
49 #define CPU_USAGE_HIGH 95
51 #define MONITOR_INTERVAL 500 // ms
52 #define MONITOR_MINIMAL_LIFETIME 60 * 1000 // ms
54 #define WORKER_CREATION_MAX_PER_SEC 10
56 /* The exponent to apply to the gain. 1.0 means to use linear gain,
57 * higher values will enhance large moves and damp small ones.
59 #define HILL_CLIMBING_GAIN_EXPONENT 2.0
61 /* The 'cost' of a thread. 0 means drive for increased throughput regardless
62 * of thread count, higher values bias more against higher thread counts.
64 #define HILL_CLIMBING_BIAS 0.15
66 #define HILL_CLIMBING_WAVE_PERIOD 4
67 #define HILL_CLIMBING_MAX_WAVE_MAGNITUDE 20
68 #define HILL_CLIMBING_WAVE_MAGNITUDE_MULTIPLIER 1.0
69 #define HILL_CLIMBING_WAVE_HISTORY_SIZE 8
70 #define HILL_CLIMBING_TARGET_SIGNAL_TO_NOISE_RATIO 3.0
71 #define HILL_CLIMBING_MAX_CHANGE_PER_SECOND 4
72 #define HILL_CLIMBING_MAX_CHANGE_PER_SAMPLE 20
73 #define HILL_CLIMBING_SAMPLE_INTERVAL_LOW 10
74 #define HILL_CLIMBING_SAMPLE_INTERVAL_HIGH 200
75 #define HILL_CLIMBING_ERROR_SMOOTHING_FACTOR 0.01
76 #define HILL_CLIMBING_MAX_SAMPLE_ERROR_PERCENT 0.15
80 gint16 max_working; /* determined by heuristic */
81 gint16 active; /* executing worker_thread */
82 gint16 working; /* actively executing worker_thread, not parked */
83 gint16 parked; /* parked */
90 /* Number of outstanding jobs */
91 gint32 outstanding_request;
92 /* Number of currently executing jobs */
94 /* Signalled when threadpool_jobs + outstanding_request is 0 */
95 /* Protected by threadpool->domains_lock */
96 MonoCoopCond cleanup_cond;
99 typedef MonoInternalThread ThreadPoolWorkingThread;
103 gint32 samples_to_measure;
104 gdouble target_throughput_ratio;
105 gdouble target_signal_to_noise_ratio;
106 gdouble max_change_per_second;
107 gdouble max_change_per_sample;
108 gint32 max_thread_wave_magnitude;
109 gint32 sample_interval_low;
110 gdouble thread_magnitude_multiplier;
111 gint32 sample_interval_high;
112 gdouble throughput_error_smoothing_factor;
113 gdouble gain_exponent;
114 gdouble max_sample_error;
116 gdouble current_control_setting;
117 gint64 total_samples;
118 gint16 last_thread_count;
119 gdouble elapsed_since_last_change;
120 gdouble completions_since_last_change;
122 gdouble average_throughput_noise;
125 gdouble *thread_counts;
127 guint32 current_sample_interval;
128 gpointer random_interval_generator;
130 gint32 accumulated_completion_count;
131 gdouble accumulated_sample_duration;
132 } ThreadPoolHillClimbing;
135 ThreadPoolCounter counters;
137 GPtrArray *domains; // ThreadPoolDomain* []
138 MonoCoopMutex domains_lock;
140 GPtrArray *working_threads; // ThreadPoolWorkingThread* []
141 gint32 parked_threads_count;
142 MonoCoopCond parked_threads_cond;
143 MonoCoopMutex active_threads_lock; /* protect access to working_threads and parked_threads */
145 guint32 worker_creation_current_second;
146 guint32 worker_creation_current_count;
147 MonoCoopMutex worker_creation_lock;
149 gint32 heuristic_completions;
150 gint64 heuristic_sample_start;
151 gint64 heuristic_last_dequeue; // ms
152 gint64 heuristic_last_adjustment; // ms
153 gint64 heuristic_adjustment_interval; // ms
154 ThreadPoolHillClimbing heuristic_hill_climbing;
155 MonoCoopMutex heuristic_lock;
157 gint32 limit_worker_min;
158 gint32 limit_worker_max;
162 MonoCpuUsageState *cpu_usage_state;
165 /* suspended by the debugger */
171 TRANSITION_INITIALIZING,
172 TRANSITION_RANDOM_MOVE,
173 TRANSITION_CLIMBING_MOVE,
174 TRANSITION_CHANGE_POINT,
175 TRANSITION_STABILIZING,
176 TRANSITION_STARVATION,
177 TRANSITION_THREAD_TIMED_OUT,
178 TRANSITION_UNDEFINED,
179 } ThreadPoolHeuristicStateTransition;
181 static mono_lazy_init_t status = MONO_LAZY_INIT_STATUS_NOT_INITIALIZED;
184 MONITOR_STATUS_REQUESTED,
185 MONITOR_STATUS_WAITING_FOR_REQUEST,
186 MONITOR_STATUS_NOT_RUNNING,
189 static gint32 monitor_status = MONITOR_STATUS_NOT_RUNNING;
191 static ThreadPool* threadpool;
193 #define COUNTER_CHECK(counter) \
195 g_assert (counter._.max_working > 0); \
196 g_assert (counter._.working >= 0); \
197 g_assert (counter._.active >= 0); \
200 #define COUNTER_READ() (InterlockedRead64 (&threadpool->counters.as_gint64))
202 #define COUNTER_ATOMIC(var,block) \
204 ThreadPoolCounter __old; \
206 g_assert (threadpool); \
207 __old.as_gint64 = COUNTER_READ (); \
210 COUNTER_CHECK (var); \
211 } while (InterlockedCompareExchange64 (&threadpool->counters.as_gint64, (var).as_gint64, __old.as_gint64) != __old.as_gint64); \
214 #define COUNTER_TRY_ATOMIC(res,var,block) \
216 ThreadPoolCounter __old; \
218 g_assert (threadpool); \
219 __old.as_gint64 = COUNTER_READ (); \
223 COUNTER_CHECK (var); \
224 (res) = InterlockedCompareExchange64 (&threadpool->counters.as_gint64, (var).as_gint64, __old.as_gint64) == __old.as_gint64; \
231 mono_coop_mutex_lock (&threadpool->domains_lock);
235 domains_unlock (void)
237 mono_coop_mutex_unlock (&threadpool->domains_lock);
244 return mono_rand_init (NULL, 0);
248 rand_next (gpointer *handle, guint32 min, guint32 max)
252 mono_rand_try_get_uint32 (handle, &val, min, max, &error);
253 // FIXME handle error
254 mono_error_assert_ok (&error);
259 rand_free (gpointer handle)
261 mono_rand_close (handle);
267 ThreadPoolHillClimbing *hc;
268 const char *threads_per_cpu_env;
269 gint threads_per_cpu;
272 g_assert (!threadpool);
273 threadpool = g_new0 (ThreadPool, 1);
274 g_assert (threadpool);
276 threadpool->domains = g_ptr_array_new ();
277 mono_coop_mutex_init (&threadpool->domains_lock);
279 threadpool->parked_threads_count = 0;
280 mono_coop_cond_init (&threadpool->parked_threads_cond);
281 threadpool->working_threads = g_ptr_array_new ();
282 mono_coop_mutex_init (&threadpool->active_threads_lock);
284 threadpool->worker_creation_current_second = -1;
285 mono_coop_mutex_init (&threadpool->worker_creation_lock);
287 threadpool->heuristic_adjustment_interval = 10;
288 mono_coop_mutex_init (&threadpool->heuristic_lock);
292 hc = &threadpool->heuristic_hill_climbing;
294 hc->wave_period = HILL_CLIMBING_WAVE_PERIOD;
295 hc->max_thread_wave_magnitude = HILL_CLIMBING_MAX_WAVE_MAGNITUDE;
296 hc->thread_magnitude_multiplier = (gdouble) HILL_CLIMBING_WAVE_MAGNITUDE_MULTIPLIER;
297 hc->samples_to_measure = hc->wave_period * HILL_CLIMBING_WAVE_HISTORY_SIZE;
298 hc->target_throughput_ratio = (gdouble) HILL_CLIMBING_BIAS;
299 hc->target_signal_to_noise_ratio = (gdouble) HILL_CLIMBING_TARGET_SIGNAL_TO_NOISE_RATIO;
300 hc->max_change_per_second = (gdouble) HILL_CLIMBING_MAX_CHANGE_PER_SECOND;
301 hc->max_change_per_sample = (gdouble) HILL_CLIMBING_MAX_CHANGE_PER_SAMPLE;
302 hc->sample_interval_low = HILL_CLIMBING_SAMPLE_INTERVAL_LOW;
303 hc->sample_interval_high = HILL_CLIMBING_SAMPLE_INTERVAL_HIGH;
304 hc->throughput_error_smoothing_factor = (gdouble) HILL_CLIMBING_ERROR_SMOOTHING_FACTOR;
305 hc->gain_exponent = (gdouble) HILL_CLIMBING_GAIN_EXPONENT;
306 hc->max_sample_error = (gdouble) HILL_CLIMBING_MAX_SAMPLE_ERROR_PERCENT;
307 hc->current_control_setting = 0;
308 hc->total_samples = 0;
309 hc->last_thread_count = 0;
310 hc->average_throughput_noise = 0;
311 hc->elapsed_since_last_change = 0;
312 hc->accumulated_completion_count = 0;
313 hc->accumulated_sample_duration = 0;
314 hc->samples = g_new0 (gdouble, hc->samples_to_measure);
315 hc->thread_counts = g_new0 (gdouble, hc->samples_to_measure);
316 hc->random_interval_generator = rand_create ();
317 hc->current_sample_interval = rand_next (&hc->random_interval_generator, hc->sample_interval_low, hc->sample_interval_high);
319 if (!(threads_per_cpu_env = g_getenv ("MONO_THREADS_PER_CPU")))
322 threads_per_cpu = CLAMP (atoi (threads_per_cpu_env), 1, 50);
324 threads_count = mono_cpu_count () * threads_per_cpu;
326 threadpool->limit_worker_min = threadpool->limit_io_min = threads_count;
328 #if defined (PLATFORM_ANDROID) || defined (HOST_IOS)
329 threadpool->limit_worker_max = threadpool->limit_io_max = CLAMP (threads_count * 100, MIN (threads_count, 200), MAX (threads_count, 200));
331 threadpool->limit_worker_max = threadpool->limit_io_max = threads_count * 100;
334 threadpool->counters._.max_working = threadpool->limit_worker_min;
336 threadpool->cpu_usage_state = g_new0 (MonoCpuUsageState, 1);
338 threadpool->suspended = FALSE;
341 static void worker_kill (ThreadPoolWorkingThread *thread);
348 /* we make the assumption along the code that we are
349 * cleaning up only if the runtime is shutting down */
350 g_assert (mono_runtime_is_shutting_down ());
352 while (monitor_status != MONITOR_STATUS_NOT_RUNNING)
353 mono_thread_info_sleep (1, NULL);
355 mono_coop_mutex_lock (&threadpool->active_threads_lock);
357 /* stop all threadpool->working_threads */
358 for (i = 0; i < threadpool->working_threads->len; ++i)
359 worker_kill ((ThreadPoolWorkingThread*) g_ptr_array_index (threadpool->working_threads, i));
361 /* unpark all threadpool->parked_threads */
362 mono_coop_cond_broadcast (&threadpool->parked_threads_cond);
364 mono_coop_mutex_unlock (&threadpool->active_threads_lock);
368 mono_threadpool_ms_enqueue_work_item (MonoDomain *domain, MonoObject *work_item, MonoError *error)
370 static MonoClass *threadpool_class = NULL;
371 static MonoMethod *unsafe_queue_custom_work_item_method = NULL;
372 MonoDomain *current_domain;
376 mono_error_init (error);
377 g_assert (work_item);
379 if (!threadpool_class)
380 threadpool_class = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "ThreadPool");
382 if (!unsafe_queue_custom_work_item_method)
383 unsafe_queue_custom_work_item_method = mono_class_get_method_from_name (threadpool_class, "UnsafeQueueCustomWorkItem", 2);
384 g_assert (unsafe_queue_custom_work_item_method);
388 args [0] = (gpointer) work_item;
389 args [1] = (gpointer) &f;
391 current_domain = mono_domain_get ();
392 if (current_domain == domain) {
393 mono_runtime_invoke_checked (unsafe_queue_custom_work_item_method, NULL, args, error);
394 return_val_if_nok (error, FALSE);
396 mono_thread_push_appdomain_ref (domain);
397 if (mono_domain_set (domain, FALSE)) {
398 mono_runtime_invoke_checked (unsafe_queue_custom_work_item_method, NULL, args, error);
399 if (!is_ok (error)) {
400 mono_thread_pop_appdomain_ref ();
403 mono_domain_set (current_domain, TRUE);
405 mono_thread_pop_appdomain_ref ();
410 /* LOCKING: domains_lock must be held */
412 tpdomain_add (ThreadPoolDomain *tpdomain)
418 len = threadpool->domains->len;
419 for (i = 0; i < len; ++i) {
420 if (g_ptr_array_index (threadpool->domains, i) == tpdomain)
425 g_ptr_array_add (threadpool->domains, tpdomain);
428 /* LOCKING: domains_lock must be held. */
430 tpdomain_remove (ThreadPoolDomain *tpdomain)
433 return g_ptr_array_remove (threadpool->domains, tpdomain);
436 /* LOCKING: domains_lock must be held */
437 static ThreadPoolDomain *
438 tpdomain_get (MonoDomain *domain, gboolean create)
441 ThreadPoolDomain *tpdomain;
445 for (i = 0; i < threadpool->domains->len; ++i) {
446 ThreadPoolDomain *tpdomain;
448 tpdomain = (ThreadPoolDomain *)g_ptr_array_index (threadpool->domains, i);
449 if (tpdomain->domain == domain)
456 tpdomain = g_new0 (ThreadPoolDomain, 1);
457 tpdomain->domain = domain;
458 mono_coop_cond_init (&tpdomain->cleanup_cond);
460 tpdomain_add (tpdomain);
466 tpdomain_free (ThreadPoolDomain *tpdomain)
471 /* LOCKING: domains_lock must be held */
473 domain_any_has_request (void)
477 for (i = 0; i < threadpool->domains->len; ++i) {
478 ThreadPoolDomain *tmp = (ThreadPoolDomain *)g_ptr_array_index (threadpool->domains, i);
479 if (tmp->outstanding_request > 0)
486 /* LOCKING: domains_lock must be held */
487 static ThreadPoolDomain *
488 tpdomain_get_next (ThreadPoolDomain *current)
490 ThreadPoolDomain *tpdomain = NULL;
493 len = threadpool->domains->len;
495 guint i, current_idx = -1;
497 for (i = 0; i < len; ++i) {
498 if (current == g_ptr_array_index (threadpool->domains, i)) {
503 g_assert (current_idx != (guint)-1);
505 for (i = current_idx + 1; i < len + current_idx + 1; ++i) {
506 ThreadPoolDomain *tmp = (ThreadPoolDomain *)g_ptr_array_index (threadpool->domains, i % len);
507 if (tmp->outstanding_request > 0) {
518 worker_wait_interrupt (gpointer data)
520 mono_coop_mutex_lock (&threadpool->active_threads_lock);
521 mono_coop_cond_signal (&threadpool->parked_threads_cond);
522 mono_coop_mutex_unlock (&threadpool->active_threads_lock);
525 /* return TRUE if timeout, FALSE otherwise (worker unpark or interrupt) */
529 gboolean timeout = FALSE;
531 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] current worker parking", mono_native_thread_id_get ());
533 mono_gc_set_skip_thread (TRUE);
535 mono_coop_mutex_lock (&threadpool->active_threads_lock);
537 if (!mono_runtime_is_shutting_down ()) {
538 static gpointer rand_handle = NULL;
539 MonoInternalThread *thread_internal;
540 gboolean interrupted = FALSE;
543 rand_handle = rand_create ();
544 g_assert (rand_handle);
546 thread_internal = mono_thread_internal_current ();
547 g_assert (thread_internal);
549 threadpool->parked_threads_count += 1;
550 g_ptr_array_remove_fast (threadpool->working_threads, thread_internal);
552 mono_thread_info_install_interrupt (worker_wait_interrupt, NULL, &interrupted);
556 if (mono_coop_cond_timedwait (&threadpool->parked_threads_cond, &threadpool->active_threads_lock, rand_next (&rand_handle, 5 * 1000, 60 * 1000)) != 0)
559 mono_thread_info_uninstall_interrupt (&interrupted);
562 g_ptr_array_add (threadpool->working_threads, thread_internal);
563 threadpool->parked_threads_count -= 1;
566 mono_coop_mutex_unlock (&threadpool->active_threads_lock);
568 mono_gc_set_skip_thread (FALSE);
570 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] current worker unparking, timeout? %s", mono_native_thread_id_get (), timeout ? "yes" : "no");
576 worker_try_unpark (void)
578 gboolean res = FALSE;
580 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try unpark worker", mono_native_thread_id_get ());
582 mono_coop_mutex_lock (&threadpool->active_threads_lock);
583 if (threadpool->parked_threads_count > 0) {
584 mono_coop_cond_signal (&threadpool->parked_threads_cond);
587 mono_coop_mutex_unlock (&threadpool->active_threads_lock);
589 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try unpark worker, success? %s", mono_native_thread_id_get (), res ? "yes" : "no");
595 worker_kill (ThreadPoolWorkingThread *thread)
597 if (thread == mono_thread_internal_current ())
600 mono_thread_internal_abort ((MonoInternalThread*) thread);
604 worker_thread (gpointer data)
607 MonoInternalThread *thread;
608 ThreadPoolDomain *tpdomain, *previous_tpdomain;
609 ThreadPoolCounter counter;
610 gboolean retire = FALSE;
612 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_THREADPOOL, "[%p] worker starting", mono_native_thread_id_get ());
614 g_assert (threadpool);
616 thread = mono_thread_internal_current ();
619 mono_thread_set_name_internal (thread, mono_string_new (mono_get_root_domain (), "Threadpool worker"), FALSE, &error);
620 mono_error_assert_ok (&error);
622 mono_coop_mutex_lock (&threadpool->active_threads_lock);
623 g_ptr_array_add (threadpool->working_threads, thread);
624 mono_coop_mutex_unlock (&threadpool->active_threads_lock);
626 previous_tpdomain = NULL;
630 while (!mono_runtime_is_shutting_down ()) {
633 if ((thread->state & (ThreadState_AbortRequested | ThreadState_SuspendRequested)) != 0) {
635 mono_thread_interruption_checkpoint ();
639 if (retire || !(tpdomain = tpdomain_get_next (previous_tpdomain))) {
642 COUNTER_ATOMIC (counter, {
643 counter._.working --;
648 timeout = worker_park ();
651 COUNTER_ATOMIC (counter, {
652 counter._.working ++;
662 /* The tpdomain->domain might have unloaded, while this thread was parked */
663 previous_tpdomain = NULL;
668 tpdomain->outstanding_request --;
669 g_assert (tpdomain->outstanding_request >= 0);
671 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] worker running in domain %p (outstanding requests %d) ",
672 mono_native_thread_id_get (), tpdomain->domain, tpdomain->outstanding_request);
674 g_assert (tpdomain->domain);
675 g_assert (tpdomain->threadpool_jobs >= 0);
676 tpdomain->threadpool_jobs ++;
679 * This is needed so there is always an lmf frame in the runtime invoke call below,
680 * so ThreadAbortExceptions are caught even if the thread is in native code.
682 mono_defaults.threadpool_perform_wait_callback_method->save_lmf = TRUE;
686 mono_thread_push_appdomain_ref (tpdomain->domain);
687 if (mono_domain_set (tpdomain->domain, FALSE)) {
688 MonoObject *exc = NULL, *res;
690 res = mono_runtime_try_invoke (mono_defaults.threadpool_perform_wait_callback_method, NULL, NULL, &exc, &error);
691 if (exc || !mono_error_ok(&error)) {
693 exc = (MonoObject *) mono_error_convert_to_exception (&error);
695 mono_error_cleanup (&error);
696 mono_thread_internal_unhandled_exception (exc);
697 } else if (res && *(MonoBoolean*) mono_object_unbox (res) == FALSE)
700 mono_thread_clr_state (thread, (MonoThreadState)~ThreadState_Background);
701 if (!mono_thread_test_state (thread , ThreadState_Background))
702 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
704 mono_domain_set (mono_get_root_domain (), TRUE);
706 mono_thread_pop_appdomain_ref ();
710 tpdomain->threadpool_jobs --;
711 g_assert (tpdomain->threadpool_jobs >= 0);
713 if (tpdomain->outstanding_request + tpdomain->threadpool_jobs == 0 && mono_domain_is_unloading (tpdomain->domain)) {
716 removed = tpdomain_remove (tpdomain);
719 mono_coop_cond_signal (&tpdomain->cleanup_cond);
723 previous_tpdomain = tpdomain;
728 mono_coop_mutex_lock (&threadpool->active_threads_lock);
729 g_ptr_array_remove_fast (threadpool->working_threads, thread);
730 mono_coop_mutex_unlock (&threadpool->active_threads_lock);
732 COUNTER_ATOMIC (counter, {
737 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_THREADPOOL, "[%p] worker finishing", mono_native_thread_id_get ());
741 worker_try_create (void)
743 ThreadPoolCounter counter;
744 MonoInternalThread *thread;
745 gint64 current_ticks;
748 mono_coop_mutex_lock (&threadpool->worker_creation_lock);
750 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker", mono_native_thread_id_get ());
751 current_ticks = mono_100ns_ticks ();
752 now = current_ticks / (10 * 1000 * 1000);
753 if (0 == current_ticks) {
754 g_warning ("failed to get 100ns ticks");
756 if (threadpool->worker_creation_current_second != now) {
757 threadpool->worker_creation_current_second = now;
758 threadpool->worker_creation_current_count = 0;
760 g_assert (threadpool->worker_creation_current_count <= WORKER_CREATION_MAX_PER_SEC);
761 if (threadpool->worker_creation_current_count == WORKER_CREATION_MAX_PER_SEC) {
762 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker, failed: maximum number of worker created per second reached, current count = %d",
763 mono_native_thread_id_get (), threadpool->worker_creation_current_count);
764 mono_coop_mutex_unlock (&threadpool->worker_creation_lock);
770 COUNTER_ATOMIC (counter, {
771 if (counter._.working >= counter._.max_working) {
772 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker, failed: maximum number of working threads reached",
773 mono_native_thread_id_get ());
774 mono_coop_mutex_unlock (&threadpool->worker_creation_lock);
777 counter._.working ++;
782 if ((thread = mono_thread_create_internal (mono_get_root_domain (), worker_thread, NULL, TRUE, 0, &error)) != NULL) {
783 threadpool->worker_creation_current_count += 1;
785 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker, created %p, now = %d count = %d", mono_native_thread_id_get (), GUINT_TO_POINTER(thread->tid), now, threadpool->worker_creation_current_count);
786 mono_coop_mutex_unlock (&threadpool->worker_creation_lock);
790 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker, failed: could not create thread due to %s", mono_native_thread_id_get (), mono_error_get_message (&error));
791 mono_error_cleanup (&error);
793 COUNTER_ATOMIC (counter, {
794 counter._.working --;
798 mono_coop_mutex_unlock (&threadpool->worker_creation_lock);
802 static void monitor_ensure_running (void);
805 worker_request (MonoDomain *domain)
807 ThreadPoolDomain *tpdomain;
810 g_assert (threadpool);
812 if (mono_runtime_is_shutting_down ())
817 /* synchronize check with worker_thread */
818 if (mono_domain_is_unloading (domain)) {
823 tpdomain = tpdomain_get (domain, TRUE);
825 tpdomain->outstanding_request ++;
827 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] request worker, domain = %p, outstanding_request = %d",
828 mono_native_thread_id_get (), tpdomain->domain, tpdomain->outstanding_request);
832 if (threadpool->suspended)
835 monitor_ensure_running ();
837 if (worker_try_unpark ()) {
838 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] request worker, unparked", mono_native_thread_id_get ());
842 if (worker_try_create ()) {
843 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] request worker, created", mono_native_thread_id_get ());
847 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] request worker, failed", mono_native_thread_id_get ());
852 monitor_should_keep_running (void)
854 static gint64 last_should_keep_running = -1;
856 g_assert (monitor_status == MONITOR_STATUS_WAITING_FOR_REQUEST || monitor_status == MONITOR_STATUS_REQUESTED);
858 if (InterlockedExchange (&monitor_status, MONITOR_STATUS_WAITING_FOR_REQUEST) == MONITOR_STATUS_WAITING_FOR_REQUEST) {
859 gboolean should_keep_running = TRUE, force_should_keep_running = FALSE;
861 if (mono_runtime_is_shutting_down ()) {
862 should_keep_running = FALSE;
865 if (!domain_any_has_request ())
866 should_keep_running = FALSE;
869 if (!should_keep_running) {
870 if (last_should_keep_running == -1 || mono_100ns_ticks () - last_should_keep_running < MONITOR_MINIMAL_LIFETIME * 1000 * 10) {
871 should_keep_running = force_should_keep_running = TRUE;
876 if (should_keep_running) {
877 if (last_should_keep_running == -1 || !force_should_keep_running)
878 last_should_keep_running = mono_100ns_ticks ();
880 last_should_keep_running = -1;
881 if (InterlockedCompareExchange (&monitor_status, MONITOR_STATUS_NOT_RUNNING, MONITOR_STATUS_WAITING_FOR_REQUEST) == MONITOR_STATUS_WAITING_FOR_REQUEST)
886 g_assert (monitor_status == MONITOR_STATUS_WAITING_FOR_REQUEST || monitor_status == MONITOR_STATUS_REQUESTED);
892 monitor_sufficient_delay_since_last_dequeue (void)
896 g_assert (threadpool);
898 if (threadpool->cpu_usage < CPU_USAGE_LOW) {
899 threshold = MONITOR_INTERVAL;
901 ThreadPoolCounter counter;
902 counter.as_gint64 = COUNTER_READ();
903 threshold = counter._.max_working * MONITOR_INTERVAL * 2;
906 return mono_msec_ticks () >= threadpool->heuristic_last_dequeue + threshold;
909 static void hill_climbing_force_change (gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition);
912 monitor_thread (void)
914 MonoInternalThread *current_thread = mono_thread_internal_current ();
917 mono_cpu_usage (threadpool->cpu_usage_state);
919 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, started", mono_native_thread_id_get ());
922 ThreadPoolCounter counter;
923 gboolean limit_worker_max_reached;
924 gint32 interval_left = MONITOR_INTERVAL;
925 gint32 awake = 0; /* number of spurious awakes we tolerate before doing a round of rebalancing */
927 g_assert (monitor_status != MONITOR_STATUS_NOT_RUNNING);
929 mono_gc_set_skip_thread (TRUE);
933 gboolean alerted = FALSE;
935 if (mono_runtime_is_shutting_down ())
938 ts = mono_msec_ticks ();
939 if (mono_thread_info_sleep (interval_left, &alerted) == 0)
941 interval_left -= mono_msec_ticks () - ts;
943 mono_gc_set_skip_thread (FALSE);
944 if ((current_thread->state & (ThreadState_StopRequested | ThreadState_SuspendRequested)) != 0)
945 mono_thread_interruption_checkpoint ();
946 mono_gc_set_skip_thread (TRUE);
947 } while (interval_left > 0 && ++awake < 10);
949 mono_gc_set_skip_thread (FALSE);
951 if (threadpool->suspended)
954 if (mono_runtime_is_shutting_down ())
958 if (!domain_any_has_request ()) {
964 threadpool->cpu_usage = mono_cpu_usage (threadpool->cpu_usage_state);
966 if (!monitor_sufficient_delay_since_last_dequeue ())
969 limit_worker_max_reached = FALSE;
971 COUNTER_ATOMIC (counter, {
972 if (counter._.max_working >= threadpool->limit_worker_max) {
973 limit_worker_max_reached = TRUE;
976 counter._.max_working ++;
979 if (limit_worker_max_reached)
982 hill_climbing_force_change (counter._.max_working, TRANSITION_STARVATION);
984 for (i = 0; i < 5; ++i) {
985 if (mono_runtime_is_shutting_down ())
988 if (worker_try_unpark ()) {
989 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, unparked", mono_native_thread_id_get ());
993 if (worker_try_create ()) {
994 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, created", mono_native_thread_id_get ());
998 } while (monitor_should_keep_running ());
1000 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, finished", mono_native_thread_id_get ());
1004 monitor_ensure_running (void)
1008 switch (monitor_status) {
1009 case MONITOR_STATUS_REQUESTED:
1011 case MONITOR_STATUS_WAITING_FOR_REQUEST:
1012 InterlockedCompareExchange (&monitor_status, MONITOR_STATUS_REQUESTED, MONITOR_STATUS_WAITING_FOR_REQUEST);
1014 case MONITOR_STATUS_NOT_RUNNING:
1015 if (mono_runtime_is_shutting_down ())
1017 if (InterlockedCompareExchange (&monitor_status, MONITOR_STATUS_REQUESTED, MONITOR_STATUS_NOT_RUNNING) == MONITOR_STATUS_NOT_RUNNING) {
1018 if (!mono_thread_create_internal (mono_get_root_domain (), monitor_thread, NULL, TRUE, SMALL_STACK, &error)) {
1019 monitor_status = MONITOR_STATUS_NOT_RUNNING;
1020 mono_error_cleanup (&error);
1025 default: g_assert_not_reached ();
1031 hill_climbing_change_thread_count (gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition)
1033 ThreadPoolHillClimbing *hc;
1035 g_assert (threadpool);
1037 hc = &threadpool->heuristic_hill_climbing;
1039 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_THREADPOOL, "[%p] hill climbing, change max number of threads %d", mono_native_thread_id_get (), new_thread_count);
1041 hc->last_thread_count = new_thread_count;
1042 hc->current_sample_interval = rand_next (&hc->random_interval_generator, hc->sample_interval_low, hc->sample_interval_high);
1043 hc->elapsed_since_last_change = 0;
1044 hc->completions_since_last_change = 0;
1048 hill_climbing_force_change (gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition)
1050 ThreadPoolHillClimbing *hc;
1052 g_assert (threadpool);
1054 hc = &threadpool->heuristic_hill_climbing;
1056 if (new_thread_count != hc->last_thread_count) {
1057 hc->current_control_setting += new_thread_count - hc->last_thread_count;
1058 hill_climbing_change_thread_count (new_thread_count, transition);
1062 static double_complex
1063 hill_climbing_get_wave_component (gdouble *samples, guint sample_count, gdouble period)
1065 ThreadPoolHillClimbing *hc;
1066 gdouble w, cosine, sine, coeff, q0, q1, q2;
1069 g_assert (threadpool);
1070 g_assert (sample_count >= period);
1071 g_assert (period >= 2);
1073 hc = &threadpool->heuristic_hill_climbing;
1075 w = 2.0 * M_PI / period;
1078 coeff = 2.0 * cosine;
1081 for (i = 0; i < sample_count; ++i) {
1082 q0 = coeff * q1 - q2 + samples [(hc->total_samples - sample_count + i) % hc->samples_to_measure];
1087 return mono_double_complex_scalar_div (mono_double_complex_make (q1 - q2 * cosine, (q2 * sine)), ((gdouble)sample_count));
1091 hill_climbing_update (gint16 current_thread_count, guint32 sample_duration, gint32 completions, gint64 *adjustment_interval)
1093 ThreadPoolHillClimbing *hc;
1094 ThreadPoolHeuristicStateTransition transition;
1096 gdouble throughput_error_estimate;
1102 gint new_thread_wave_magnitude;
1103 gint new_thread_count;
1104 double_complex thread_wave_component;
1105 double_complex throughput_wave_component;
1106 double_complex ratio;
1108 g_assert (threadpool);
1109 g_assert (adjustment_interval);
1111 hc = &threadpool->heuristic_hill_climbing;
1113 /* If someone changed the thread count without telling us, update our records accordingly. */
1114 if (current_thread_count != hc->last_thread_count)
1115 hill_climbing_force_change (current_thread_count, TRANSITION_INITIALIZING);
1117 /* Update the cumulative stats for this thread count */
1118 hc->elapsed_since_last_change += sample_duration;
1119 hc->completions_since_last_change += completions;
1121 /* Add in any data we've already collected about this sample */
1122 sample_duration += hc->accumulated_sample_duration;
1123 completions += hc->accumulated_completion_count;
1125 /* We need to make sure we're collecting reasonably accurate data. Since we're just counting the end
1126 * of each work item, we are goinng to be missing some data about what really happened during the
1127 * sample interval. The count produced by each thread includes an initial work item that may have
1128 * started well before the start of the interval, and each thread may have been running some new
1129 * work item for some time before the end of the interval, which did not yet get counted. So
1130 * our count is going to be off by +/- threadCount workitems.
1132 * The exception is that the thread that reported to us last time definitely wasn't running any work
1133 * at that time, and the thread that's reporting now definitely isn't running a work item now. So
1134 * we really only need to consider threadCount-1 threads.
1136 * Thus the percent error in our count is +/- (threadCount-1)/numCompletions.
1138 * We cannot rely on the frequency-domain analysis we'll be doing later to filter out this error, because
1139 * of the way it accumulates over time. If this sample is off by, say, 33% in the negative direction,
1140 * then the next one likely will be too. The one after that will include the sum of the completions
1141 * we missed in the previous samples, and so will be 33% positive. So every three samples we'll have
1142 * two "low" samples and one "high" sample. This will appear as periodic variation right in the frequency
1143 * range we're targeting, which will not be filtered by the frequency-domain translation. */
1144 if (hc->total_samples > 0 && ((current_thread_count - 1.0) / completions) >= hc->max_sample_error) {
1145 /* Not accurate enough yet. Let's accumulate the data so
1146 * far, and tell the ThreadPool to collect a little more. */
1147 hc->accumulated_sample_duration = sample_duration;
1148 hc->accumulated_completion_count = completions;
1149 *adjustment_interval = 10;
1150 return current_thread_count;
1153 /* We've got enouugh data for our sample; reset our accumulators for next time. */
1154 hc->accumulated_sample_duration = 0;
1155 hc->accumulated_completion_count = 0;
1157 /* Add the current thread count and throughput sample to our history. */
1158 throughput = ((gdouble) completions) / sample_duration;
1160 sample_index = hc->total_samples % hc->samples_to_measure;
1161 hc->samples [sample_index] = throughput;
1162 hc->thread_counts [sample_index] = current_thread_count;
1163 hc->total_samples ++;
1165 /* Set up defaults for our metrics. */
1166 thread_wave_component = mono_double_complex_make(0, 0);
1167 throughput_wave_component = mono_double_complex_make(0, 0);
1168 throughput_error_estimate = 0;
1169 ratio = mono_double_complex_make(0, 0);
1172 transition = TRANSITION_WARMUP;
1174 /* How many samples will we use? It must be at least the three wave periods we're looking for, and it must also
1175 * be a whole multiple of the primary wave's period; otherwise the frequency we're looking for will fall between
1176 * two frequency bands in the Fourier analysis, and we won't be able to measure it accurately. */
1177 sample_count = ((gint) MIN (hc->total_samples - 1, hc->samples_to_measure) / hc->wave_period) * hc->wave_period;
1179 if (sample_count > hc->wave_period) {
1181 gdouble average_throughput;
1182 gdouble average_thread_count;
1183 gdouble sample_sum = 0;
1184 gdouble thread_sum = 0;
1186 /* Average the throughput and thread count samples, so we can scale the wave magnitudes later. */
1187 for (i = 0; i < sample_count; ++i) {
1188 guint j = (hc->total_samples - sample_count + i) % hc->samples_to_measure;
1189 sample_sum += hc->samples [j];
1190 thread_sum += hc->thread_counts [j];
1193 average_throughput = sample_sum / sample_count;
1194 average_thread_count = thread_sum / sample_count;
1196 if (average_throughput > 0 && average_thread_count > 0) {
1197 gdouble noise_for_confidence, adjacent_period_1, adjacent_period_2;
1199 /* Calculate the periods of the adjacent frequency bands we'll be using to
1200 * measure noise levels. We want the two adjacent Fourier frequency bands. */
1201 adjacent_period_1 = sample_count / (((gdouble) sample_count) / ((gdouble) hc->wave_period) + 1);
1202 adjacent_period_2 = sample_count / (((gdouble) sample_count) / ((gdouble) hc->wave_period) - 1);
1204 /* Get the the three different frequency components of the throughput (scaled by average
1205 * throughput). Our "error" estimate (the amount of noise that might be present in the
1206 * frequency band we're really interested in) is the average of the adjacent bands. */
1207 throughput_wave_component = mono_double_complex_scalar_div (hill_climbing_get_wave_component (hc->samples, sample_count, hc->wave_period), average_throughput);
1208 throughput_error_estimate = cabs (mono_double_complex_scalar_div (hill_climbing_get_wave_component (hc->samples, sample_count, adjacent_period_1), average_throughput));
1210 if (adjacent_period_2 <= sample_count) {
1211 throughput_error_estimate = MAX (throughput_error_estimate, cabs (mono_double_complex_scalar_div (hill_climbing_get_wave_component (
1212 hc->samples, sample_count, adjacent_period_2), average_throughput)));
1215 /* Do the same for the thread counts, so we have something to compare to. We don't
1216 * measure thread count noise, because there is none; these are exact measurements. */
1217 thread_wave_component = mono_double_complex_scalar_div (hill_climbing_get_wave_component (hc->thread_counts, sample_count, hc->wave_period), average_thread_count);
1219 /* Update our moving average of the throughput noise. We'll use this
1220 * later as feedback to determine the new size of the thread wave. */
1221 if (hc->average_throughput_noise == 0) {
1222 hc->average_throughput_noise = throughput_error_estimate;
1224 hc->average_throughput_noise = (hc->throughput_error_smoothing_factor * throughput_error_estimate)
1225 + ((1.0 + hc->throughput_error_smoothing_factor) * hc->average_throughput_noise);
1228 if (cabs (thread_wave_component) > 0) {
1229 /* Adjust the throughput wave so it's centered around the target wave,
1230 * and then calculate the adjusted throughput/thread ratio. */
1231 ratio = mono_double_complex_div (mono_double_complex_sub (throughput_wave_component, mono_double_complex_scalar_mul(thread_wave_component, hc->target_throughput_ratio)), thread_wave_component);
1232 transition = TRANSITION_CLIMBING_MOVE;
1234 ratio = mono_double_complex_make (0, 0);
1235 transition = TRANSITION_STABILIZING;
1238 noise_for_confidence = MAX (hc->average_throughput_noise, throughput_error_estimate);
1239 if (noise_for_confidence > 0) {
1240 confidence = cabs (thread_wave_component) / noise_for_confidence / hc->target_signal_to_noise_ratio;
1242 /* there is no noise! */
1248 /* We use just the real part of the complex ratio we just calculated. If the throughput signal
1249 * is exactly in phase with the thread signal, this will be the same as taking the magnitude of
1250 * the complex move and moving that far up. If they're 180 degrees out of phase, we'll move
1251 * backward (because this indicates that our changes are having the opposite of the intended effect).
1252 * If they're 90 degrees out of phase, we won't move at all, because we can't tell wether we're
1253 * having a negative or positive effect on throughput. */
1254 move = creal (ratio);
1255 move = CLAMP (move, -1.0, 1.0);
1257 /* Apply our confidence multiplier. */
1258 move *= CLAMP (confidence, -1.0, 1.0);
1260 /* Now apply non-linear gain, such that values around zero are attenuated, while higher values
1261 * are enhanced. This allows us to move quickly if we're far away from the target, but more slowly
1262 * if we're getting close, giving us rapid ramp-up without wild oscillations around the target. */
1263 gain = hc->max_change_per_second * sample_duration;
1264 move = pow (fabs (move), hc->gain_exponent) * (move >= 0.0 ? 1 : -1) * gain;
1265 move = MIN (move, hc->max_change_per_sample);
1267 /* If the result was positive, and CPU is > 95%, refuse the move. */
1268 if (move > 0.0 && threadpool->cpu_usage > CPU_USAGE_HIGH)
1271 /* Apply the move to our control setting. */
1272 hc->current_control_setting += move;
1274 /* Calculate the new thread wave magnitude, which is based on the moving average we've been keeping of the
1275 * throughput error. This average starts at zero, so we'll start with a nice safe little wave at first. */
1276 new_thread_wave_magnitude = (gint)(0.5 + (hc->current_control_setting * hc->average_throughput_noise
1277 * hc->target_signal_to_noise_ratio * hc->thread_magnitude_multiplier * 2.0));
1278 new_thread_wave_magnitude = CLAMP (new_thread_wave_magnitude, 1, hc->max_thread_wave_magnitude);
1280 /* Make sure our control setting is within the ThreadPool's limits. */
1281 hc->current_control_setting = CLAMP (hc->current_control_setting, threadpool->limit_worker_min, threadpool->limit_worker_max - new_thread_wave_magnitude);
1283 /* Calculate the new thread count (control setting + square wave). */
1284 new_thread_count = (gint)(hc->current_control_setting + new_thread_wave_magnitude * ((hc->total_samples / (hc->wave_period / 2)) % 2));
1286 /* Make sure the new thread count doesn't exceed the ThreadPool's limits. */
1287 new_thread_count = CLAMP (new_thread_count, threadpool->limit_worker_min, threadpool->limit_worker_max);
1289 if (new_thread_count != current_thread_count)
1290 hill_climbing_change_thread_count (new_thread_count, transition);
1292 if (creal (ratio) < 0.0 && new_thread_count == threadpool->limit_worker_min)
1293 *adjustment_interval = (gint)(0.5 + hc->current_sample_interval * (10.0 * MAX (-1.0 * creal (ratio), 1.0)));
1295 *adjustment_interval = hc->current_sample_interval;
1297 return new_thread_count;
1301 heuristic_notify_work_completed (void)
1303 g_assert (threadpool);
1305 InterlockedIncrement (&threadpool->heuristic_completions);
1306 threadpool->heuristic_last_dequeue = mono_msec_ticks ();
1310 heuristic_should_adjust (void)
1312 g_assert (threadpool);
1314 if (threadpool->heuristic_last_dequeue > threadpool->heuristic_last_adjustment + threadpool->heuristic_adjustment_interval) {
1315 ThreadPoolCounter counter;
1316 counter.as_gint64 = COUNTER_READ();
1317 if (counter._.working <= counter._.max_working)
1325 heuristic_adjust (void)
1327 g_assert (threadpool);
1329 if (mono_coop_mutex_trylock (&threadpool->heuristic_lock) == 0) {
1330 gint32 completions = InterlockedExchange (&threadpool->heuristic_completions, 0);
1331 gint64 sample_end = mono_msec_ticks ();
1332 gint64 sample_duration = sample_end - threadpool->heuristic_sample_start;
1334 if (sample_duration >= threadpool->heuristic_adjustment_interval / 2) {
1335 ThreadPoolCounter counter;
1336 gint16 new_thread_count;
1338 counter.as_gint64 = COUNTER_READ ();
1339 new_thread_count = hill_climbing_update (counter._.max_working, sample_duration, completions, &threadpool->heuristic_adjustment_interval);
1341 COUNTER_ATOMIC (counter, { counter._.max_working = new_thread_count; });
1343 if (new_thread_count > counter._.max_working)
1344 worker_request (mono_domain_get ());
1346 threadpool->heuristic_sample_start = sample_end;
1347 threadpool->heuristic_last_adjustment = mono_msec_ticks ();
1350 mono_coop_mutex_unlock (&threadpool->heuristic_lock);
1355 mono_threadpool_ms_cleanup (void)
1357 #ifndef DISABLE_SOCKETS
1358 mono_threadpool_ms_io_cleanup ();
1360 mono_lazy_cleanup (&status, cleanup);
1364 mono_threadpool_ms_begin_invoke (MonoDomain *domain, MonoObject *target, MonoMethod *method, gpointer *params, MonoError *error)
1366 static MonoClass *async_call_klass = NULL;
1367 MonoMethodMessage *message;
1368 MonoAsyncResult *async_result;
1369 MonoAsyncCall *async_call;
1370 MonoDelegate *async_callback = NULL;
1371 MonoObject *state = NULL;
1373 if (!async_call_klass)
1374 async_call_klass = mono_class_load_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
1376 mono_lazy_initialize (&status, initialize);
1378 mono_error_init (error);
1380 message = mono_method_call_message_new (method, params, mono_get_delegate_invoke (method->klass), (params != NULL) ? (&async_callback) : NULL, (params != NULL) ? (&state) : NULL, error);
1381 return_val_if_nok (error, NULL);
1383 async_call = (MonoAsyncCall*) mono_object_new_checked (domain, async_call_klass, error);
1384 return_val_if_nok (error, NULL);
1386 MONO_OBJECT_SETREF (async_call, msg, message);
1387 MONO_OBJECT_SETREF (async_call, state, state);
1389 if (async_callback) {
1390 MONO_OBJECT_SETREF (async_call, cb_method, mono_get_delegate_invoke (((MonoObject*) async_callback)->vtable->klass));
1391 MONO_OBJECT_SETREF (async_call, cb_target, async_callback);
1394 async_result = mono_async_result_new (domain, NULL, async_call->state, NULL, (MonoObject*) async_call, error);
1395 return_val_if_nok (error, NULL);
1396 MONO_OBJECT_SETREF (async_result, async_delegate, target);
1398 mono_threadpool_ms_enqueue_work_item (domain, (MonoObject*) async_result, error);
1399 return_val_if_nok (error, NULL);
1401 return async_result;
1405 mono_threadpool_ms_end_invoke (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc, MonoError *error)
1409 mono_error_init (error);
1411 g_assert (out_args);
1416 /* check if already finished */
1417 mono_monitor_enter ((MonoObject*) ares);
1419 if (ares->endinvoke_called) {
1420 mono_error_set_invalid_operation(error, "Delegate EndInvoke method called more than once");
1421 mono_monitor_exit ((MonoObject*) ares);
1425 ares->endinvoke_called = 1;
1427 /* wait until we are really finished */
1428 if (ares->completed) {
1429 mono_monitor_exit ((MonoObject *) ares);
1431 gpointer wait_event;
1433 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle*) ares->handle);
1435 wait_event = mono_w32event_create (TRUE, FALSE);
1436 g_assert(wait_event);
1437 MonoWaitHandle *wait_handle = mono_wait_handle_new (mono_object_domain (ares), wait_event, error);
1438 if (!is_ok (error)) {
1439 CloseHandle (wait_event);
1442 MONO_OBJECT_SETREF (ares, handle, (MonoObject*) wait_handle);
1444 mono_monitor_exit ((MonoObject*) ares);
1447 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
1449 mono_w32handle_wait_one (wait_event, INFINITE, TRUE);
1454 ac = (MonoAsyncCall*) ares->object_data;
1457 *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1458 *out_args = ac->out_args;
1463 mono_threadpool_ms_remove_domain_jobs (MonoDomain *domain, int timeout)
1466 ThreadPoolDomain *tpdomain;
1470 g_assert (timeout >= -1);
1472 g_assert (mono_domain_is_unloading (domain));
1475 end = mono_msec_ticks () + timeout;
1477 #ifndef DISABLE_SOCKETS
1478 mono_threadpool_ms_io_remove_domain_jobs (domain);
1479 if (timeout != -1) {
1480 if (mono_msec_ticks () > end)
1486 * Wait for all threads which execute jobs in the domain to exit.
1487 * The is_unloading () check in worker_request () ensures that
1488 * no new jobs are added after we enter the lock below.
1490 mono_lazy_initialize (&status, initialize);
1493 tpdomain = tpdomain_get (domain, FALSE);
1501 while (tpdomain->outstanding_request + tpdomain->threadpool_jobs > 0) {
1502 if (timeout == -1) {
1503 mono_coop_cond_wait (&tpdomain->cleanup_cond, &threadpool->domains_lock);
1508 now = mono_msec_ticks();
1514 res = mono_coop_cond_timedwait (&tpdomain->cleanup_cond, &threadpool->domains_lock, end - now);
1522 /* Remove from the list the worker threads look at */
1523 tpdomain_remove (tpdomain);
1527 mono_coop_cond_destroy (&tpdomain->cleanup_cond);
1528 tpdomain_free (tpdomain);
1534 mono_threadpool_ms_suspend (void)
1537 threadpool->suspended = TRUE;
1541 mono_threadpool_ms_resume (void)
1544 threadpool->suspended = FALSE;
1548 ves_icall_System_Threading_ThreadPool_GetAvailableThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
1550 ThreadPoolCounter counter;
1552 if (!worker_threads || !completion_port_threads)
1555 mono_lazy_initialize (&status, initialize);
1557 counter.as_gint64 = COUNTER_READ ();
1559 *worker_threads = MAX (0, threadpool->limit_worker_max - counter._.active);
1560 *completion_port_threads = threadpool->limit_io_max;
1564 ves_icall_System_Threading_ThreadPool_GetMinThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
1566 if (!worker_threads || !completion_port_threads)
1569 mono_lazy_initialize (&status, initialize);
1571 *worker_threads = threadpool->limit_worker_min;
1572 *completion_port_threads = threadpool->limit_io_min;
1576 ves_icall_System_Threading_ThreadPool_GetMaxThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
1578 if (!worker_threads || !completion_port_threads)
1581 mono_lazy_initialize (&status, initialize);
1583 *worker_threads = threadpool->limit_worker_max;
1584 *completion_port_threads = threadpool->limit_io_max;
1588 ves_icall_System_Threading_ThreadPool_SetMinThreadsNative (gint32 worker_threads, gint32 completion_port_threads)
1590 mono_lazy_initialize (&status, initialize);
1592 if (worker_threads <= 0 || worker_threads > threadpool->limit_worker_max)
1594 if (completion_port_threads <= 0 || completion_port_threads > threadpool->limit_io_max)
1597 threadpool->limit_worker_min = worker_threads;
1598 threadpool->limit_io_min = completion_port_threads;
1604 ves_icall_System_Threading_ThreadPool_SetMaxThreadsNative (gint32 worker_threads, gint32 completion_port_threads)
1606 gint cpu_count = mono_cpu_count ();
1608 mono_lazy_initialize (&status, initialize);
1610 if (worker_threads < threadpool->limit_worker_min || worker_threads < cpu_count)
1612 if (completion_port_threads < threadpool->limit_io_min || completion_port_threads < cpu_count)
1615 threadpool->limit_worker_max = worker_threads;
1616 threadpool->limit_io_max = completion_port_threads;
1622 ves_icall_System_Threading_ThreadPool_InitializeVMTp (MonoBoolean *enable_worker_tracking)
1624 if (enable_worker_tracking) {
1625 // TODO implement some kind of switch to have the possibily to use it
1626 *enable_worker_tracking = FALSE;
1629 mono_lazy_initialize (&status, initialize);
1633 ves_icall_System_Threading_ThreadPool_NotifyWorkItemComplete (void)
1635 ThreadPoolCounter counter;
1637 if (mono_domain_is_unloading (mono_domain_get ()) || mono_runtime_is_shutting_down ())
1640 heuristic_notify_work_completed ();
1642 if (heuristic_should_adjust ())
1643 heuristic_adjust ();
1645 counter.as_gint64 = COUNTER_READ ();
1646 return counter._.working <= counter._.max_working;
1650 ves_icall_System_Threading_ThreadPool_NotifyWorkItemProgressNative (void)
1652 heuristic_notify_work_completed ();
1654 if (heuristic_should_adjust ())
1655 heuristic_adjust ();
1659 ves_icall_System_Threading_ThreadPool_ReportThreadStatus (MonoBoolean is_working)
1663 mono_error_set_not_implemented (&error, "");
1664 mono_error_set_pending_exception (&error);
1668 ves_icall_System_Threading_ThreadPool_RequestWorkerThread (void)
1670 return worker_request (mono_domain_get ());
1673 MonoBoolean G_GNUC_UNUSED
1674 ves_icall_System_Threading_ThreadPool_PostQueuedCompletionStatus (MonoNativeOverlapped *native_overlapped)
1676 /* This copy the behavior of the current Mono implementation */
1678 mono_error_set_not_implemented (&error, "");
1679 mono_error_set_pending_exception (&error);
1683 MonoBoolean G_GNUC_UNUSED
1684 ves_icall_System_Threading_ThreadPool_BindIOCompletionCallbackNative (gpointer file_handle)
1686 /* This copy the behavior of the current Mono implementation */
1690 MonoBoolean G_GNUC_UNUSED
1691 ves_icall_System_Threading_ThreadPool_IsThreadPoolHosted (void)