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 gint32 outstanding_request;
93 typedef MonoInternalThread ThreadPoolWorkingThread;
97 gint32 samples_to_measure;
98 gdouble target_throughput_ratio;
99 gdouble target_signal_to_noise_ratio;
100 gdouble max_change_per_second;
101 gdouble max_change_per_sample;
102 gint32 max_thread_wave_magnitude;
103 gint32 sample_interval_low;
104 gdouble thread_magnitude_multiplier;
105 gint32 sample_interval_high;
106 gdouble throughput_error_smoothing_factor;
107 gdouble gain_exponent;
108 gdouble max_sample_error;
110 gdouble current_control_setting;
111 gint64 total_samples;
112 gint16 last_thread_count;
113 gdouble elapsed_since_last_change;
114 gdouble completions_since_last_change;
116 gdouble average_throughput_noise;
119 gdouble *thread_counts;
121 guint32 current_sample_interval;
122 gpointer random_interval_generator;
124 gint32 accumulated_completion_count;
125 gdouble accumulated_sample_duration;
126 } ThreadPoolHillClimbing;
129 ThreadPoolCounter counters;
131 GPtrArray *domains; // ThreadPoolDomain* []
132 MonoCoopMutex domains_lock;
134 GPtrArray *working_threads; // ThreadPoolWorkingThread* []
135 gint32 parked_threads_count;
136 MonoCoopCond parked_threads_cond;
137 MonoCoopMutex active_threads_lock; /* protect access to working_threads and parked_threads */
139 guint32 worker_creation_current_second;
140 guint32 worker_creation_current_count;
141 MonoCoopMutex worker_creation_lock;
143 gint32 heuristic_completions;
144 gint64 heuristic_sample_start;
145 gint64 heuristic_last_dequeue; // ms
146 gint64 heuristic_last_adjustment; // ms
147 gint64 heuristic_adjustment_interval; // ms
148 ThreadPoolHillClimbing heuristic_hill_climbing;
149 MonoCoopMutex heuristic_lock;
151 gint32 limit_worker_min;
152 gint32 limit_worker_max;
156 MonoCpuUsageState *cpu_usage_state;
159 /* suspended by the debugger */
166 } ThreadPoolDomainCleanupSemaphore;
170 TRANSITION_INITIALIZING,
171 TRANSITION_RANDOM_MOVE,
172 TRANSITION_CLIMBING_MOVE,
173 TRANSITION_CHANGE_POINT,
174 TRANSITION_STABILIZING,
175 TRANSITION_STARVATION,
176 TRANSITION_THREAD_TIMED_OUT,
177 TRANSITION_UNDEFINED,
178 } ThreadPoolHeuristicStateTransition;
180 static mono_lazy_init_t status = MONO_LAZY_INIT_STATUS_NOT_INITIALIZED;
183 MONITOR_STATUS_REQUESTED,
184 MONITOR_STATUS_WAITING_FOR_REQUEST,
185 MONITOR_STATUS_NOT_RUNNING,
188 static gint32 monitor_status = MONITOR_STATUS_NOT_RUNNING;
190 static ThreadPool* threadpool;
192 #define COUNTER_CHECK(counter) \
194 g_assert (counter._.max_working > 0); \
195 g_assert (counter._.working >= 0); \
196 g_assert (counter._.active >= 0); \
199 #define COUNTER_READ() (InterlockedRead64 (&threadpool->counters.as_gint64))
201 #define COUNTER_ATOMIC(var,block) \
203 ThreadPoolCounter __old; \
205 g_assert (threadpool); \
206 __old.as_gint64 = COUNTER_READ (); \
209 COUNTER_CHECK (var); \
210 } while (InterlockedCompareExchange64 (&threadpool->counters.as_gint64, (var).as_gint64, __old.as_gint64) != __old.as_gint64); \
213 #define COUNTER_TRY_ATOMIC(res,var,block) \
215 ThreadPoolCounter __old; \
217 g_assert (threadpool); \
218 __old.as_gint64 = COUNTER_READ (); \
222 COUNTER_CHECK (var); \
223 (res) = InterlockedCompareExchange64 (&threadpool->counters.as_gint64, (var).as_gint64, __old.as_gint64) == __old.as_gint64; \
231 return mono_rand_init (NULL, 0);
235 rand_next (gpointer *handle, guint32 min, guint32 max)
239 mono_rand_try_get_uint32 (handle, &val, min, max, &error);
240 // FIXME handle error
241 mono_error_assert_ok (&error);
246 rand_free (gpointer handle)
248 mono_rand_close (handle);
254 ThreadPoolHillClimbing *hc;
255 const char *threads_per_cpu_env;
256 gint threads_per_cpu;
259 g_assert (!threadpool);
260 threadpool = g_new0 (ThreadPool, 1);
261 g_assert (threadpool);
263 threadpool->domains = g_ptr_array_new ();
264 mono_coop_mutex_init (&threadpool->domains_lock);
266 threadpool->parked_threads_count = 0;
267 mono_coop_cond_init (&threadpool->parked_threads_cond);
268 threadpool->working_threads = g_ptr_array_new ();
269 mono_coop_mutex_init (&threadpool->active_threads_lock);
271 threadpool->worker_creation_current_second = -1;
272 mono_coop_mutex_init (&threadpool->worker_creation_lock);
274 threadpool->heuristic_adjustment_interval = 10;
275 mono_coop_mutex_init (&threadpool->heuristic_lock);
279 hc = &threadpool->heuristic_hill_climbing;
281 hc->wave_period = HILL_CLIMBING_WAVE_PERIOD;
282 hc->max_thread_wave_magnitude = HILL_CLIMBING_MAX_WAVE_MAGNITUDE;
283 hc->thread_magnitude_multiplier = (gdouble) HILL_CLIMBING_WAVE_MAGNITUDE_MULTIPLIER;
284 hc->samples_to_measure = hc->wave_period * HILL_CLIMBING_WAVE_HISTORY_SIZE;
285 hc->target_throughput_ratio = (gdouble) HILL_CLIMBING_BIAS;
286 hc->target_signal_to_noise_ratio = (gdouble) HILL_CLIMBING_TARGET_SIGNAL_TO_NOISE_RATIO;
287 hc->max_change_per_second = (gdouble) HILL_CLIMBING_MAX_CHANGE_PER_SECOND;
288 hc->max_change_per_sample = (gdouble) HILL_CLIMBING_MAX_CHANGE_PER_SAMPLE;
289 hc->sample_interval_low = HILL_CLIMBING_SAMPLE_INTERVAL_LOW;
290 hc->sample_interval_high = HILL_CLIMBING_SAMPLE_INTERVAL_HIGH;
291 hc->throughput_error_smoothing_factor = (gdouble) HILL_CLIMBING_ERROR_SMOOTHING_FACTOR;
292 hc->gain_exponent = (gdouble) HILL_CLIMBING_GAIN_EXPONENT;
293 hc->max_sample_error = (gdouble) HILL_CLIMBING_MAX_SAMPLE_ERROR_PERCENT;
294 hc->current_control_setting = 0;
295 hc->total_samples = 0;
296 hc->last_thread_count = 0;
297 hc->average_throughput_noise = 0;
298 hc->elapsed_since_last_change = 0;
299 hc->accumulated_completion_count = 0;
300 hc->accumulated_sample_duration = 0;
301 hc->samples = g_new0 (gdouble, hc->samples_to_measure);
302 hc->thread_counts = g_new0 (gdouble, hc->samples_to_measure);
303 hc->random_interval_generator = rand_create ();
304 hc->current_sample_interval = rand_next (&hc->random_interval_generator, hc->sample_interval_low, hc->sample_interval_high);
306 if (!(threads_per_cpu_env = g_getenv ("MONO_THREADS_PER_CPU")))
309 threads_per_cpu = CLAMP (atoi (threads_per_cpu_env), 1, 50);
311 threads_count = mono_cpu_count () * threads_per_cpu;
313 threadpool->limit_worker_min = threadpool->limit_io_min = threads_count;
315 #if defined (PLATFORM_ANDROID) || defined (HOST_IOS)
316 threadpool->limit_worker_max = threadpool->limit_io_max = CLAMP (threads_count * 100, MIN (threads_count, 200), MAX (threads_count, 200));
318 threadpool->limit_worker_max = threadpool->limit_io_max = threads_count * 100;
321 threadpool->counters._.max_working = threadpool->limit_worker_min;
323 threadpool->cpu_usage_state = g_new0 (MonoCpuUsageState, 1);
325 threadpool->suspended = FALSE;
328 static void worker_kill (ThreadPoolWorkingThread *thread);
335 /* we make the assumption along the code that we are
336 * cleaning up only if the runtime is shutting down */
337 g_assert (mono_runtime_is_shutting_down ());
339 while (monitor_status != MONITOR_STATUS_NOT_RUNNING)
340 mono_thread_info_sleep (1, NULL);
342 mono_coop_mutex_lock (&threadpool->active_threads_lock);
344 /* stop all threadpool->working_threads */
345 for (i = 0; i < threadpool->working_threads->len; ++i)
346 worker_kill ((ThreadPoolWorkingThread*) g_ptr_array_index (threadpool->working_threads, i));
348 /* unpark all threadpool->parked_threads */
349 mono_coop_cond_broadcast (&threadpool->parked_threads_cond);
351 mono_coop_mutex_unlock (&threadpool->active_threads_lock);
355 mono_threadpool_ms_enqueue_work_item (MonoDomain *domain, MonoObject *work_item, MonoError *error)
357 static MonoClass *threadpool_class = NULL;
358 static MonoMethod *unsafe_queue_custom_work_item_method = NULL;
359 MonoDomain *current_domain;
363 mono_error_init (error);
364 g_assert (work_item);
366 if (!threadpool_class)
367 threadpool_class = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "ThreadPool");
369 if (!unsafe_queue_custom_work_item_method)
370 unsafe_queue_custom_work_item_method = mono_class_get_method_from_name (threadpool_class, "UnsafeQueueCustomWorkItem", 2);
371 g_assert (unsafe_queue_custom_work_item_method);
375 args [0] = (gpointer) work_item;
376 args [1] = (gpointer) &f;
378 current_domain = mono_domain_get ();
379 if (current_domain == domain) {
380 mono_runtime_invoke_checked (unsafe_queue_custom_work_item_method, NULL, args, error);
381 return_val_if_nok (error, FALSE);
383 mono_thread_push_appdomain_ref (domain);
384 if (mono_domain_set (domain, FALSE)) {
385 mono_runtime_invoke_checked (unsafe_queue_custom_work_item_method, NULL, args, error);
386 if (!is_ok (error)) {
387 mono_thread_pop_appdomain_ref ();
390 mono_domain_set (current_domain, TRUE);
392 mono_thread_pop_appdomain_ref ();
397 /* LOCKING: threadpool->domains_lock must be held */
399 domain_add (ThreadPoolDomain *tpdomain)
405 len = threadpool->domains->len;
406 for (i = 0; i < len; ++i) {
407 if (g_ptr_array_index (threadpool->domains, i) == tpdomain)
412 g_ptr_array_add (threadpool->domains, tpdomain);
415 /* LOCKING: threadpool->domains_lock must be held */
417 domain_remove (ThreadPoolDomain *tpdomain)
420 return g_ptr_array_remove (threadpool->domains, tpdomain);
423 /* LOCKING: threadpool->domains_lock must be held */
424 static ThreadPoolDomain *
425 domain_get (MonoDomain *domain, gboolean create)
427 ThreadPoolDomain *tpdomain = NULL;
432 for (i = 0; i < threadpool->domains->len; ++i) {
433 tpdomain = (ThreadPoolDomain *)g_ptr_array_index (threadpool->domains, i);
434 if (tpdomain->domain == domain)
439 ThreadPoolDomainCleanupSemaphore *cleanup_semaphore;
440 cleanup_semaphore = g_new0 (ThreadPoolDomainCleanupSemaphore, 1);
441 cleanup_semaphore->ref = 2;
442 mono_coop_sem_init (&cleanup_semaphore->sem, 0);
444 g_assert(!domain->cleanup_semaphore);
445 domain->cleanup_semaphore = cleanup_semaphore;
447 tpdomain = g_new0 (ThreadPoolDomain, 1);
448 tpdomain->domain = domain;
449 domain_add (tpdomain);
456 domain_free (ThreadPoolDomain *tpdomain)
461 /* LOCKING: threadpool->domains_lock must be held */
463 domain_any_has_request (void)
467 for (i = 0; i < threadpool->domains->len; ++i) {
468 ThreadPoolDomain *tmp = (ThreadPoolDomain *)g_ptr_array_index (threadpool->domains, i);
469 if (tmp->outstanding_request > 0)
476 /* LOCKING: threadpool->domains_lock must be held */
477 static ThreadPoolDomain *
478 domain_get_next (ThreadPoolDomain *current)
480 ThreadPoolDomain *tpdomain = NULL;
483 len = threadpool->domains->len;
485 guint i, current_idx = -1;
487 for (i = 0; i < len; ++i) {
488 if (current == g_ptr_array_index (threadpool->domains, i)) {
493 g_assert (current_idx != (guint)-1);
495 for (i = current_idx + 1; i < len + current_idx + 1; ++i) {
496 ThreadPoolDomain *tmp = (ThreadPoolDomain *)g_ptr_array_index (threadpool->domains, i % len);
497 if (tmp->outstanding_request > 0) {
508 worker_wait_interrupt (gpointer data)
510 mono_coop_mutex_lock (&threadpool->active_threads_lock);
511 mono_coop_cond_signal (&threadpool->parked_threads_cond);
512 mono_coop_mutex_unlock (&threadpool->active_threads_lock);
515 /* return TRUE if timeout, FALSE otherwise (worker unpark or interrupt) */
519 gboolean timeout = FALSE;
521 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] current worker parking", mono_native_thread_id_get ());
523 mono_gc_set_skip_thread (TRUE);
525 mono_coop_mutex_lock (&threadpool->active_threads_lock);
527 if (!mono_runtime_is_shutting_down ()) {
528 static gpointer rand_handle = NULL;
529 MonoInternalThread *thread_internal;
530 gboolean interrupted = FALSE;
533 rand_handle = rand_create ();
534 g_assert (rand_handle);
536 thread_internal = mono_thread_internal_current ();
537 g_assert (thread_internal);
539 threadpool->parked_threads_count += 1;
540 g_ptr_array_remove_fast (threadpool->working_threads, thread_internal);
542 mono_thread_info_install_interrupt (worker_wait_interrupt, NULL, &interrupted);
546 if (mono_coop_cond_timedwait (&threadpool->parked_threads_cond, &threadpool->active_threads_lock, rand_next (&rand_handle, 5 * 1000, 60 * 1000)) != 0)
549 mono_thread_info_uninstall_interrupt (&interrupted);
552 g_ptr_array_add (threadpool->working_threads, thread_internal);
553 threadpool->parked_threads_count -= 1;
556 mono_coop_mutex_unlock (&threadpool->active_threads_lock);
558 mono_gc_set_skip_thread (FALSE);
560 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] current worker unparking, timeout? %s", mono_native_thread_id_get (), timeout ? "yes" : "no");
566 worker_try_unpark (void)
568 gboolean res = FALSE;
570 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try unpark worker", mono_native_thread_id_get ());
572 mono_coop_mutex_lock (&threadpool->active_threads_lock);
573 if (threadpool->parked_threads_count > 0) {
574 mono_coop_cond_signal (&threadpool->parked_threads_cond);
577 mono_coop_mutex_unlock (&threadpool->active_threads_lock);
579 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try unpark worker, success? %s", mono_native_thread_id_get (), res ? "yes" : "no");
585 worker_kill (ThreadPoolWorkingThread *thread)
587 if (thread == mono_thread_internal_current ())
590 mono_thread_internal_stop ((MonoInternalThread*) thread);
594 worker_thread (gpointer data)
597 MonoInternalThread *thread;
598 ThreadPoolDomain *tpdomain, *previous_tpdomain;
599 ThreadPoolCounter counter;
600 gboolean retire = FALSE;
602 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_THREADPOOL, "[%p] worker starting", mono_native_thread_id_get ());
604 g_assert (threadpool);
606 thread = mono_thread_internal_current ();
609 mono_thread_set_name_internal (thread, mono_string_new (mono_get_root_domain (), "Threadpool worker"), FALSE, &error);
610 mono_error_assert_ok (&error);
612 mono_coop_mutex_lock (&threadpool->active_threads_lock);
613 g_ptr_array_add (threadpool->working_threads, thread);
614 mono_coop_mutex_unlock (&threadpool->active_threads_lock);
616 previous_tpdomain = NULL;
618 mono_coop_mutex_lock (&threadpool->domains_lock);
620 while (!mono_runtime_is_shutting_down ()) {
623 if ((thread->state & (ThreadState_StopRequested | ThreadState_SuspendRequested)) != 0) {
624 mono_coop_mutex_unlock (&threadpool->domains_lock);
625 mono_thread_interruption_checkpoint ();
626 mono_coop_mutex_lock (&threadpool->domains_lock);
629 if (retire || !(tpdomain = domain_get_next (previous_tpdomain))) {
632 COUNTER_ATOMIC (counter, {
633 counter._.working --;
637 mono_coop_mutex_unlock (&threadpool->domains_lock);
638 timeout = worker_park ();
639 mono_coop_mutex_lock (&threadpool->domains_lock);
641 COUNTER_ATOMIC (counter, {
642 counter._.working ++;
652 /* The tpdomain->domain might have unloaded, while this thread was parked */
653 previous_tpdomain = NULL;
658 tpdomain->outstanding_request --;
659 g_assert (tpdomain->outstanding_request >= 0);
661 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] worker running in domain %p",
662 mono_native_thread_id_get (), tpdomain->domain, tpdomain->outstanding_request);
664 g_assert (tpdomain->domain);
665 g_assert (tpdomain->domain->threadpool_jobs >= 0);
666 tpdomain->domain->threadpool_jobs ++;
668 mono_coop_mutex_unlock (&threadpool->domains_lock);
670 mono_thread_push_appdomain_ref (tpdomain->domain);
671 if (mono_domain_set (tpdomain->domain, FALSE)) {
672 MonoObject *exc = NULL, *res;
674 res = mono_runtime_try_invoke (mono_defaults.threadpool_perform_wait_callback_method, NULL, NULL, &exc, &error);
675 if (exc || !mono_error_ok(&error)) {
677 exc = (MonoObject *) mono_error_convert_to_exception (&error);
679 mono_error_cleanup (&error);
680 mono_thread_internal_unhandled_exception (exc);
681 } else if (res && *(MonoBoolean*) mono_object_unbox (res) == FALSE)
684 mono_thread_clr_state (thread, (MonoThreadState)~ThreadState_Background);
685 if (!mono_thread_test_state (thread , ThreadState_Background))
686 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
688 mono_domain_set (mono_get_root_domain (), TRUE);
690 mono_thread_pop_appdomain_ref ();
692 mono_coop_mutex_lock (&threadpool->domains_lock);
694 tpdomain->domain->threadpool_jobs --;
695 g_assert (tpdomain->domain->threadpool_jobs >= 0);
697 if (tpdomain->domain->threadpool_jobs == 0 && mono_domain_is_unloading (tpdomain->domain)) {
698 ThreadPoolDomainCleanupSemaphore *cleanup_semaphore;
701 removed = domain_remove(tpdomain);
704 cleanup_semaphore = (ThreadPoolDomainCleanupSemaphore*) tpdomain->domain->cleanup_semaphore;
706 g_assert(cleanup_semaphore);
707 mono_coop_sem_post (&cleanup_semaphore->sem);
708 if (InterlockedDecrement (&cleanup_semaphore->ref) == 0) {
709 mono_coop_sem_destroy (&cleanup_semaphore->sem);
710 g_free (cleanup_semaphore);
711 tpdomain->domain->cleanup_semaphore = NULL;
714 domain_free (tpdomain);
718 previous_tpdomain = tpdomain;
721 mono_coop_mutex_unlock (&threadpool->domains_lock);
723 mono_coop_mutex_lock (&threadpool->active_threads_lock);
724 g_ptr_array_remove_fast (threadpool->working_threads, thread);
725 mono_coop_mutex_unlock (&threadpool->active_threads_lock);
727 COUNTER_ATOMIC (counter, {
732 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_THREADPOOL, "[%p] worker finishing", mono_native_thread_id_get ());
736 worker_try_create (void)
738 ThreadPoolCounter counter;
739 MonoInternalThread *thread;
740 gint64 current_ticks;
743 mono_coop_mutex_lock (&threadpool->worker_creation_lock);
745 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker", mono_native_thread_id_get ());
746 current_ticks = mono_100ns_ticks ();
747 now = current_ticks / (10 * 1000 * 1000);
748 if (0 == current_ticks) {
749 g_warning ("failed to get 100ns ticks");
751 if (threadpool->worker_creation_current_second != now) {
752 threadpool->worker_creation_current_second = now;
753 threadpool->worker_creation_current_count = 0;
755 g_assert (threadpool->worker_creation_current_count <= WORKER_CREATION_MAX_PER_SEC);
756 if (threadpool->worker_creation_current_count == WORKER_CREATION_MAX_PER_SEC) {
757 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",
758 mono_native_thread_id_get (), threadpool->worker_creation_current_count);
759 mono_coop_mutex_unlock (&threadpool->worker_creation_lock);
765 COUNTER_ATOMIC (counter, {
766 if (counter._.working >= counter._.max_working) {
767 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker, failed: maximum number of working threads reached",
768 mono_native_thread_id_get ());
769 mono_coop_mutex_unlock (&threadpool->worker_creation_lock);
772 counter._.working ++;
777 if ((thread = mono_thread_create_internal (mono_get_root_domain (), worker_thread, NULL, TRUE, 0, &error)) != NULL) {
778 threadpool->worker_creation_current_count += 1;
780 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker, created %p, now = %d count = %d", mono_native_thread_id_get (), thread->tid, now, threadpool->worker_creation_current_count);
781 mono_coop_mutex_unlock (&threadpool->worker_creation_lock);
785 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));
786 mono_error_cleanup (&error);
788 COUNTER_ATOMIC (counter, {
789 counter._.working --;
793 mono_coop_mutex_unlock (&threadpool->worker_creation_lock);
797 static void monitor_ensure_running (void);
800 worker_request (MonoDomain *domain)
802 ThreadPoolDomain *tpdomain;
805 g_assert (threadpool);
807 if (mono_runtime_is_shutting_down ())
810 mono_coop_mutex_lock (&threadpool->domains_lock);
812 /* synchronize check with worker_thread */
813 if (mono_domain_is_unloading (domain)) {
814 mono_coop_mutex_unlock (&threadpool->domains_lock);
818 tpdomain = domain_get (domain, TRUE);
820 tpdomain->outstanding_request ++;
822 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] request worker, domain = %p, outstanding_request = %d",
823 mono_native_thread_id_get (), tpdomain->domain, tpdomain->outstanding_request);
825 mono_coop_mutex_unlock (&threadpool->domains_lock);
827 if (threadpool->suspended)
830 monitor_ensure_running ();
832 if (worker_try_unpark ()) {
833 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] request worker, unparked", mono_native_thread_id_get ());
837 if (worker_try_create ()) {
838 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] request worker, created", mono_native_thread_id_get ());
842 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] request worker, failed", mono_native_thread_id_get ());
847 monitor_should_keep_running (void)
849 static gint64 last_should_keep_running = -1;
851 g_assert (monitor_status == MONITOR_STATUS_WAITING_FOR_REQUEST || monitor_status == MONITOR_STATUS_REQUESTED);
853 if (InterlockedExchange (&monitor_status, MONITOR_STATUS_WAITING_FOR_REQUEST) == MONITOR_STATUS_WAITING_FOR_REQUEST) {
854 gboolean should_keep_running = TRUE, force_should_keep_running = FALSE;
856 if (mono_runtime_is_shutting_down ()) {
857 should_keep_running = FALSE;
859 mono_coop_mutex_lock (&threadpool->domains_lock);
860 if (!domain_any_has_request ())
861 should_keep_running = FALSE;
862 mono_coop_mutex_unlock (&threadpool->domains_lock);
864 if (!should_keep_running) {
865 if (last_should_keep_running == -1 || mono_100ns_ticks () - last_should_keep_running < MONITOR_MINIMAL_LIFETIME * 1000 * 10) {
866 should_keep_running = force_should_keep_running = TRUE;
871 if (should_keep_running) {
872 if (last_should_keep_running == -1 || !force_should_keep_running)
873 last_should_keep_running = mono_100ns_ticks ();
875 last_should_keep_running = -1;
876 if (InterlockedCompareExchange (&monitor_status, MONITOR_STATUS_NOT_RUNNING, MONITOR_STATUS_WAITING_FOR_REQUEST) == MONITOR_STATUS_WAITING_FOR_REQUEST)
881 g_assert (monitor_status == MONITOR_STATUS_WAITING_FOR_REQUEST || monitor_status == MONITOR_STATUS_REQUESTED);
887 monitor_sufficient_delay_since_last_dequeue (void)
891 g_assert (threadpool);
893 if (threadpool->cpu_usage < CPU_USAGE_LOW) {
894 threshold = MONITOR_INTERVAL;
896 ThreadPoolCounter counter;
897 counter.as_gint64 = COUNTER_READ();
898 threshold = counter._.max_working * MONITOR_INTERVAL * 2;
901 return mono_msec_ticks () >= threadpool->heuristic_last_dequeue + threshold;
904 static void hill_climbing_force_change (gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition);
907 monitor_thread (void)
909 MonoInternalThread *current_thread = mono_thread_internal_current ();
912 mono_cpu_usage (threadpool->cpu_usage_state);
914 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, started", mono_native_thread_id_get ());
917 ThreadPoolCounter counter;
918 gboolean limit_worker_max_reached;
919 gint32 interval_left = MONITOR_INTERVAL;
920 gint32 awake = 0; /* number of spurious awakes we tolerate before doing a round of rebalancing */
922 g_assert (monitor_status != MONITOR_STATUS_NOT_RUNNING);
924 mono_gc_set_skip_thread (TRUE);
928 gboolean alerted = FALSE;
930 if (mono_runtime_is_shutting_down ())
933 ts = mono_msec_ticks ();
934 if (mono_thread_info_sleep (interval_left, &alerted) == 0)
936 interval_left -= mono_msec_ticks () - ts;
938 mono_gc_set_skip_thread (FALSE);
939 if ((current_thread->state & (ThreadState_StopRequested | ThreadState_SuspendRequested)) != 0)
940 mono_thread_interruption_checkpoint ();
941 mono_gc_set_skip_thread (TRUE);
942 } while (interval_left > 0 && ++awake < 10);
944 mono_gc_set_skip_thread (FALSE);
946 if (threadpool->suspended)
949 if (mono_runtime_is_shutting_down ())
952 mono_coop_mutex_lock (&threadpool->domains_lock);
953 if (!domain_any_has_request ()) {
954 mono_coop_mutex_unlock (&threadpool->domains_lock);
957 mono_coop_mutex_unlock (&threadpool->domains_lock);
959 threadpool->cpu_usage = mono_cpu_usage (threadpool->cpu_usage_state);
961 if (!monitor_sufficient_delay_since_last_dequeue ())
964 limit_worker_max_reached = FALSE;
966 COUNTER_ATOMIC (counter, {
967 if (counter._.max_working >= threadpool->limit_worker_max) {
968 limit_worker_max_reached = TRUE;
971 counter._.max_working ++;
974 if (limit_worker_max_reached)
977 hill_climbing_force_change (counter._.max_working, TRANSITION_STARVATION);
979 for (i = 0; i < 5; ++i) {
980 if (mono_runtime_is_shutting_down ())
983 if (worker_try_unpark ()) {
984 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, unparked", mono_native_thread_id_get ());
988 if (worker_try_create ()) {
989 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, created", mono_native_thread_id_get ());
993 } while (monitor_should_keep_running ());
995 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, finished", mono_native_thread_id_get ());
999 monitor_ensure_running (void)
1003 switch (monitor_status) {
1004 case MONITOR_STATUS_REQUESTED:
1006 case MONITOR_STATUS_WAITING_FOR_REQUEST:
1007 InterlockedCompareExchange (&monitor_status, MONITOR_STATUS_REQUESTED, MONITOR_STATUS_WAITING_FOR_REQUEST);
1009 case MONITOR_STATUS_NOT_RUNNING:
1010 if (mono_runtime_is_shutting_down ())
1012 if (InterlockedCompareExchange (&monitor_status, MONITOR_STATUS_REQUESTED, MONITOR_STATUS_NOT_RUNNING) == MONITOR_STATUS_NOT_RUNNING) {
1013 if (!mono_thread_create_internal (mono_get_root_domain (), monitor_thread, NULL, TRUE, SMALL_STACK, &error)) {
1014 monitor_status = MONITOR_STATUS_NOT_RUNNING;
1015 mono_error_cleanup (&error);
1020 default: g_assert_not_reached ();
1026 hill_climbing_change_thread_count (gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition)
1028 ThreadPoolHillClimbing *hc;
1030 g_assert (threadpool);
1032 hc = &threadpool->heuristic_hill_climbing;
1034 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);
1036 hc->last_thread_count = new_thread_count;
1037 hc->current_sample_interval = rand_next (&hc->random_interval_generator, hc->sample_interval_low, hc->sample_interval_high);
1038 hc->elapsed_since_last_change = 0;
1039 hc->completions_since_last_change = 0;
1043 hill_climbing_force_change (gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition)
1045 ThreadPoolHillClimbing *hc;
1047 g_assert (threadpool);
1049 hc = &threadpool->heuristic_hill_climbing;
1051 if (new_thread_count != hc->last_thread_count) {
1052 hc->current_control_setting += new_thread_count - hc->last_thread_count;
1053 hill_climbing_change_thread_count (new_thread_count, transition);
1057 static double_complex
1058 hill_climbing_get_wave_component (gdouble *samples, guint sample_count, gdouble period)
1060 ThreadPoolHillClimbing *hc;
1061 gdouble w, cosine, sine, coeff, q0, q1, q2;
1064 g_assert (threadpool);
1065 g_assert (sample_count >= period);
1066 g_assert (period >= 2);
1068 hc = &threadpool->heuristic_hill_climbing;
1070 w = 2.0 * M_PI / period;
1073 coeff = 2.0 * cosine;
1076 for (i = 0; i < sample_count; ++i) {
1077 q0 = coeff * q1 - q2 + samples [(hc->total_samples - sample_count + i) % hc->samples_to_measure];
1082 return mono_double_complex_scalar_div (mono_double_complex_make (q1 - q2 * cosine, (q2 * sine)), ((gdouble)sample_count));
1086 hill_climbing_update (gint16 current_thread_count, guint32 sample_duration, gint32 completions, gint64 *adjustment_interval)
1088 ThreadPoolHillClimbing *hc;
1089 ThreadPoolHeuristicStateTransition transition;
1091 gdouble throughput_error_estimate;
1097 gint new_thread_wave_magnitude;
1098 gint new_thread_count;
1099 double_complex thread_wave_component;
1100 double_complex throughput_wave_component;
1101 double_complex ratio;
1103 g_assert (threadpool);
1104 g_assert (adjustment_interval);
1106 hc = &threadpool->heuristic_hill_climbing;
1108 /* If someone changed the thread count without telling us, update our records accordingly. */
1109 if (current_thread_count != hc->last_thread_count)
1110 hill_climbing_force_change (current_thread_count, TRANSITION_INITIALIZING);
1112 /* Update the cumulative stats for this thread count */
1113 hc->elapsed_since_last_change += sample_duration;
1114 hc->completions_since_last_change += completions;
1116 /* Add in any data we've already collected about this sample */
1117 sample_duration += hc->accumulated_sample_duration;
1118 completions += hc->accumulated_completion_count;
1120 /* We need to make sure we're collecting reasonably accurate data. Since we're just counting the end
1121 * of each work item, we are goinng to be missing some data about what really happened during the
1122 * sample interval. The count produced by each thread includes an initial work item that may have
1123 * started well before the start of the interval, and each thread may have been running some new
1124 * work item for some time before the end of the interval, which did not yet get counted. So
1125 * our count is going to be off by +/- threadCount workitems.
1127 * The exception is that the thread that reported to us last time definitely wasn't running any work
1128 * at that time, and the thread that's reporting now definitely isn't running a work item now. So
1129 * we really only need to consider threadCount-1 threads.
1131 * Thus the percent error in our count is +/- (threadCount-1)/numCompletions.
1133 * We cannot rely on the frequency-domain analysis we'll be doing later to filter out this error, because
1134 * of the way it accumulates over time. If this sample is off by, say, 33% in the negative direction,
1135 * then the next one likely will be too. The one after that will include the sum of the completions
1136 * we missed in the previous samples, and so will be 33% positive. So every three samples we'll have
1137 * two "low" samples and one "high" sample. This will appear as periodic variation right in the frequency
1138 * range we're targeting, which will not be filtered by the frequency-domain translation. */
1139 if (hc->total_samples > 0 && ((current_thread_count - 1.0) / completions) >= hc->max_sample_error) {
1140 /* Not accurate enough yet. Let's accumulate the data so
1141 * far, and tell the ThreadPool to collect a little more. */
1142 hc->accumulated_sample_duration = sample_duration;
1143 hc->accumulated_completion_count = completions;
1144 *adjustment_interval = 10;
1145 return current_thread_count;
1148 /* We've got enouugh data for our sample; reset our accumulators for next time. */
1149 hc->accumulated_sample_duration = 0;
1150 hc->accumulated_completion_count = 0;
1152 /* Add the current thread count and throughput sample to our history. */
1153 throughput = ((gdouble) completions) / sample_duration;
1155 sample_index = hc->total_samples % hc->samples_to_measure;
1156 hc->samples [sample_index] = throughput;
1157 hc->thread_counts [sample_index] = current_thread_count;
1158 hc->total_samples ++;
1160 /* Set up defaults for our metrics. */
1161 thread_wave_component = mono_double_complex_make(0, 0);
1162 throughput_wave_component = mono_double_complex_make(0, 0);
1163 throughput_error_estimate = 0;
1164 ratio = mono_double_complex_make(0, 0);
1167 transition = TRANSITION_WARMUP;
1169 /* How many samples will we use? It must be at least the three wave periods we're looking for, and it must also
1170 * be a whole multiple of the primary wave's period; otherwise the frequency we're looking for will fall between
1171 * two frequency bands in the Fourier analysis, and we won't be able to measure it accurately. */
1172 sample_count = ((gint) MIN (hc->total_samples - 1, hc->samples_to_measure) / hc->wave_period) * hc->wave_period;
1174 if (sample_count > hc->wave_period) {
1176 gdouble average_throughput;
1177 gdouble average_thread_count;
1178 gdouble sample_sum = 0;
1179 gdouble thread_sum = 0;
1181 /* Average the throughput and thread count samples, so we can scale the wave magnitudes later. */
1182 for (i = 0; i < sample_count; ++i) {
1183 guint j = (hc->total_samples - sample_count + i) % hc->samples_to_measure;
1184 sample_sum += hc->samples [j];
1185 thread_sum += hc->thread_counts [j];
1188 average_throughput = sample_sum / sample_count;
1189 average_thread_count = thread_sum / sample_count;
1191 if (average_throughput > 0 && average_thread_count > 0) {
1192 gdouble noise_for_confidence, adjacent_period_1, adjacent_period_2;
1194 /* Calculate the periods of the adjacent frequency bands we'll be using to
1195 * measure noise levels. We want the two adjacent Fourier frequency bands. */
1196 adjacent_period_1 = sample_count / (((gdouble) sample_count) / ((gdouble) hc->wave_period) + 1);
1197 adjacent_period_2 = sample_count / (((gdouble) sample_count) / ((gdouble) hc->wave_period) - 1);
1199 /* Get the the three different frequency components of the throughput (scaled by average
1200 * throughput). Our "error" estimate (the amount of noise that might be present in the
1201 * frequency band we're really interested in) is the average of the adjacent bands. */
1202 throughput_wave_component = mono_double_complex_scalar_div (hill_climbing_get_wave_component (hc->samples, sample_count, hc->wave_period), average_throughput);
1203 throughput_error_estimate = cabs (mono_double_complex_scalar_div (hill_climbing_get_wave_component (hc->samples, sample_count, adjacent_period_1), average_throughput));
1205 if (adjacent_period_2 <= sample_count) {
1206 throughput_error_estimate = MAX (throughput_error_estimate, cabs (mono_double_complex_scalar_div (hill_climbing_get_wave_component (
1207 hc->samples, sample_count, adjacent_period_2), average_throughput)));
1210 /* Do the same for the thread counts, so we have something to compare to. We don't
1211 * measure thread count noise, because there is none; these are exact measurements. */
1212 thread_wave_component = mono_double_complex_scalar_div (hill_climbing_get_wave_component (hc->thread_counts, sample_count, hc->wave_period), average_thread_count);
1214 /* Update our moving average of the throughput noise. We'll use this
1215 * later as feedback to determine the new size of the thread wave. */
1216 if (hc->average_throughput_noise == 0) {
1217 hc->average_throughput_noise = throughput_error_estimate;
1219 hc->average_throughput_noise = (hc->throughput_error_smoothing_factor * throughput_error_estimate)
1220 + ((1.0 + hc->throughput_error_smoothing_factor) * hc->average_throughput_noise);
1223 if (cabs (thread_wave_component) > 0) {
1224 /* Adjust the throughput wave so it's centered around the target wave,
1225 * and then calculate the adjusted throughput/thread ratio. */
1226 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);
1227 transition = TRANSITION_CLIMBING_MOVE;
1229 ratio = mono_double_complex_make (0, 0);
1230 transition = TRANSITION_STABILIZING;
1233 noise_for_confidence = MAX (hc->average_throughput_noise, throughput_error_estimate);
1234 if (noise_for_confidence > 0) {
1235 confidence = cabs (thread_wave_component) / noise_for_confidence / hc->target_signal_to_noise_ratio;
1237 /* there is no noise! */
1243 /* We use just the real part of the complex ratio we just calculated. If the throughput signal
1244 * is exactly in phase with the thread signal, this will be the same as taking the magnitude of
1245 * the complex move and moving that far up. If they're 180 degrees out of phase, we'll move
1246 * backward (because this indicates that our changes are having the opposite of the intended effect).
1247 * If they're 90 degrees out of phase, we won't move at all, because we can't tell wether we're
1248 * having a negative or positive effect on throughput. */
1249 move = creal (ratio);
1250 move = CLAMP (move, -1.0, 1.0);
1252 /* Apply our confidence multiplier. */
1253 move *= CLAMP (confidence, -1.0, 1.0);
1255 /* Now apply non-linear gain, such that values around zero are attenuated, while higher values
1256 * are enhanced. This allows us to move quickly if we're far away from the target, but more slowly
1257 * if we're getting close, giving us rapid ramp-up without wild oscillations around the target. */
1258 gain = hc->max_change_per_second * sample_duration;
1259 move = pow (fabs (move), hc->gain_exponent) * (move >= 0.0 ? 1 : -1) * gain;
1260 move = MIN (move, hc->max_change_per_sample);
1262 /* If the result was positive, and CPU is > 95%, refuse the move. */
1263 if (move > 0.0 && threadpool->cpu_usage > CPU_USAGE_HIGH)
1266 /* Apply the move to our control setting. */
1267 hc->current_control_setting += move;
1269 /* Calculate the new thread wave magnitude, which is based on the moving average we've been keeping of the
1270 * throughput error. This average starts at zero, so we'll start with a nice safe little wave at first. */
1271 new_thread_wave_magnitude = (gint)(0.5 + (hc->current_control_setting * hc->average_throughput_noise
1272 * hc->target_signal_to_noise_ratio * hc->thread_magnitude_multiplier * 2.0));
1273 new_thread_wave_magnitude = CLAMP (new_thread_wave_magnitude, 1, hc->max_thread_wave_magnitude);
1275 /* Make sure our control setting is within the ThreadPool's limits. */
1276 hc->current_control_setting = CLAMP (hc->current_control_setting, threadpool->limit_worker_min, threadpool->limit_worker_max - new_thread_wave_magnitude);
1278 /* Calculate the new thread count (control setting + square wave). */
1279 new_thread_count = (gint)(hc->current_control_setting + new_thread_wave_magnitude * ((hc->total_samples / (hc->wave_period / 2)) % 2));
1281 /* Make sure the new thread count doesn't exceed the ThreadPool's limits. */
1282 new_thread_count = CLAMP (new_thread_count, threadpool->limit_worker_min, threadpool->limit_worker_max);
1284 if (new_thread_count != current_thread_count)
1285 hill_climbing_change_thread_count (new_thread_count, transition);
1287 if (creal (ratio) < 0.0 && new_thread_count == threadpool->limit_worker_min)
1288 *adjustment_interval = (gint)(0.5 + hc->current_sample_interval * (10.0 * MAX (-1.0 * creal (ratio), 1.0)));
1290 *adjustment_interval = hc->current_sample_interval;
1292 return new_thread_count;
1296 heuristic_notify_work_completed (void)
1298 g_assert (threadpool);
1300 InterlockedIncrement (&threadpool->heuristic_completions);
1301 threadpool->heuristic_last_dequeue = mono_msec_ticks ();
1305 heuristic_should_adjust (void)
1307 g_assert (threadpool);
1309 if (threadpool->heuristic_last_dequeue > threadpool->heuristic_last_adjustment + threadpool->heuristic_adjustment_interval) {
1310 ThreadPoolCounter counter;
1311 counter.as_gint64 = COUNTER_READ();
1312 if (counter._.working <= counter._.max_working)
1320 heuristic_adjust (void)
1322 g_assert (threadpool);
1324 if (mono_coop_mutex_trylock (&threadpool->heuristic_lock) == 0) {
1325 gint32 completions = InterlockedExchange (&threadpool->heuristic_completions, 0);
1326 gint64 sample_end = mono_msec_ticks ();
1327 gint64 sample_duration = sample_end - threadpool->heuristic_sample_start;
1329 if (sample_duration >= threadpool->heuristic_adjustment_interval / 2) {
1330 ThreadPoolCounter counter;
1331 gint16 new_thread_count;
1333 counter.as_gint64 = COUNTER_READ ();
1334 new_thread_count = hill_climbing_update (counter._.max_working, sample_duration, completions, &threadpool->heuristic_adjustment_interval);
1336 COUNTER_ATOMIC (counter, { counter._.max_working = new_thread_count; });
1338 if (new_thread_count > counter._.max_working)
1339 worker_request (mono_domain_get ());
1341 threadpool->heuristic_sample_start = sample_end;
1342 threadpool->heuristic_last_adjustment = mono_msec_ticks ();
1345 mono_coop_mutex_unlock (&threadpool->heuristic_lock);
1350 mono_threadpool_ms_cleanup (void)
1352 #ifndef DISABLE_SOCKETS
1353 mono_threadpool_ms_io_cleanup ();
1355 mono_lazy_cleanup (&status, cleanup);
1359 mono_threadpool_ms_begin_invoke (MonoDomain *domain, MonoObject *target, MonoMethod *method, gpointer *params, MonoError *error)
1361 static MonoClass *async_call_klass = NULL;
1362 MonoMethodMessage *message;
1363 MonoAsyncResult *async_result;
1364 MonoAsyncCall *async_call;
1365 MonoDelegate *async_callback = NULL;
1366 MonoObject *state = NULL;
1368 if (!async_call_klass)
1369 async_call_klass = mono_class_load_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
1371 mono_lazy_initialize (&status, initialize);
1373 mono_error_init (error);
1375 message = mono_method_call_message_new (method, params, mono_get_delegate_invoke (method->klass), (params != NULL) ? (&async_callback) : NULL, (params != NULL) ? (&state) : NULL, error);
1376 return_val_if_nok (error, NULL);
1378 async_call = (MonoAsyncCall*) mono_object_new_checked (domain, async_call_klass, error);
1379 return_val_if_nok (error, NULL);
1381 MONO_OBJECT_SETREF (async_call, msg, message);
1382 MONO_OBJECT_SETREF (async_call, state, state);
1384 if (async_callback) {
1385 MONO_OBJECT_SETREF (async_call, cb_method, mono_get_delegate_invoke (((MonoObject*) async_callback)->vtable->klass));
1386 MONO_OBJECT_SETREF (async_call, cb_target, async_callback);
1389 async_result = mono_async_result_new (domain, NULL, async_call->state, NULL, (MonoObject*) async_call, error);
1390 return_val_if_nok (error, NULL);
1391 MONO_OBJECT_SETREF (async_result, async_delegate, target);
1393 mono_threadpool_ms_enqueue_work_item (domain, (MonoObject*) async_result, error);
1394 return_val_if_nok (error, NULL);
1396 return async_result;
1400 mono_threadpool_ms_end_invoke (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc, MonoError *error)
1404 mono_error_init (error);
1406 g_assert (out_args);
1411 /* check if already finished */
1412 mono_monitor_enter ((MonoObject*) ares);
1414 if (ares->endinvoke_called) {
1415 mono_error_set_invalid_operation(error, "Delegate EndInvoke method called more than once");
1416 mono_monitor_exit ((MonoObject*) ares);
1420 ares->endinvoke_called = 1;
1422 /* wait until we are really finished */
1423 if (ares->completed) {
1424 mono_monitor_exit ((MonoObject *) ares);
1426 gpointer wait_event;
1428 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle*) ares->handle);
1430 wait_event = mono_w32event_create (TRUE, FALSE);
1431 g_assert(wait_event);
1432 MonoWaitHandle *wait_handle = mono_wait_handle_new (mono_object_domain (ares), wait_event, error);
1433 if (!is_ok (error)) {
1434 CloseHandle (wait_event);
1437 MONO_OBJECT_SETREF (ares, handle, (MonoObject*) wait_handle);
1439 mono_monitor_exit ((MonoObject*) ares);
1441 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
1445 ac = (MonoAsyncCall*) ares->object_data;
1448 *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1449 *out_args = ac->out_args;
1454 mono_threadpool_ms_remove_domain_jobs (MonoDomain *domain, int timeout)
1458 ThreadPoolDomain *tpdomain;
1459 ThreadPoolDomainCleanupSemaphore *cleanup_semaphore;
1462 g_assert (timeout >= -1);
1464 g_assert (mono_domain_is_unloading (domain));
1467 end = mono_msec_ticks () + timeout;
1469 #ifndef DISABLE_SOCKETS
1470 mono_threadpool_ms_io_remove_domain_jobs (domain);
1471 if (timeout != -1) {
1472 if (mono_msec_ticks () > end)
1478 * There might be some threads out that could be about to execute stuff from the given domain.
1479 * We avoid that by waiting on a semaphore to be pulsed by the thread that reaches zero.
1480 * The semaphore is only created for domains which queued threadpool jobs.
1481 * We always wait on the semaphore rather than ensuring domain->threadpool_jobs is 0.
1482 * There may be pending outstanding requests which will create new jobs.
1483 * The semaphore is signaled the threadpool domain has been removed from list
1484 * and we know no more jobs for the domain will be processed.
1487 mono_lazy_initialize(&status, initialize);
1488 mono_coop_mutex_lock(&threadpool->domains_lock);
1490 tpdomain = domain_get (domain, FALSE);
1491 if (!tpdomain || tpdomain->outstanding_request == 0) {
1492 mono_coop_mutex_unlock(&threadpool->domains_lock);
1496 mono_coop_mutex_unlock(&threadpool->domains_lock);
1498 g_assert (domain->cleanup_semaphore);
1500 cleanup_semaphore = (ThreadPoolDomainCleanupSemaphore*) domain->cleanup_semaphore;
1502 if (timeout == -1) {
1503 res = mono_coop_sem_wait (&cleanup_semaphore->sem, MONO_SEM_FLAGS_NONE);
1504 g_assert (res == MONO_SEM_TIMEDWAIT_RET_SUCCESS);
1506 now = mono_msec_ticks();
1509 res = mono_coop_sem_timedwait (&cleanup_semaphore->sem, end - now, MONO_SEM_FLAGS_NONE);
1512 if (InterlockedDecrement (&cleanup_semaphore->ref) == 0) {
1513 mono_coop_sem_destroy (&cleanup_semaphore->sem);
1514 g_free (cleanup_semaphore);
1515 domain->cleanup_semaphore = NULL;
1518 return res == MONO_SEM_TIMEDWAIT_RET_SUCCESS;
1522 mono_threadpool_ms_suspend (void)
1525 threadpool->suspended = TRUE;
1529 mono_threadpool_ms_resume (void)
1532 threadpool->suspended = FALSE;
1536 ves_icall_System_Threading_ThreadPool_GetAvailableThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
1538 ThreadPoolCounter counter;
1540 if (!worker_threads || !completion_port_threads)
1543 mono_lazy_initialize (&status, initialize);
1545 counter.as_gint64 = COUNTER_READ ();
1547 *worker_threads = MAX (0, threadpool->limit_worker_max - counter._.active);
1548 *completion_port_threads = threadpool->limit_io_max;
1552 ves_icall_System_Threading_ThreadPool_GetMinThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
1554 if (!worker_threads || !completion_port_threads)
1557 mono_lazy_initialize (&status, initialize);
1559 *worker_threads = threadpool->limit_worker_min;
1560 *completion_port_threads = threadpool->limit_io_min;
1564 ves_icall_System_Threading_ThreadPool_GetMaxThreadsNative (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_max;
1572 *completion_port_threads = threadpool->limit_io_max;
1576 ves_icall_System_Threading_ThreadPool_SetMinThreadsNative (gint32 worker_threads, gint32 completion_port_threads)
1578 mono_lazy_initialize (&status, initialize);
1580 if (worker_threads <= 0 || worker_threads > threadpool->limit_worker_max)
1582 if (completion_port_threads <= 0 || completion_port_threads > threadpool->limit_io_max)
1585 threadpool->limit_worker_min = worker_threads;
1586 threadpool->limit_io_min = completion_port_threads;
1592 ves_icall_System_Threading_ThreadPool_SetMaxThreadsNative (gint32 worker_threads, gint32 completion_port_threads)
1594 gint cpu_count = mono_cpu_count ();
1596 mono_lazy_initialize (&status, initialize);
1598 if (worker_threads < threadpool->limit_worker_min || worker_threads < cpu_count)
1600 if (completion_port_threads < threadpool->limit_io_min || completion_port_threads < cpu_count)
1603 threadpool->limit_worker_max = worker_threads;
1604 threadpool->limit_io_max = completion_port_threads;
1610 ves_icall_System_Threading_ThreadPool_InitializeVMTp (MonoBoolean *enable_worker_tracking)
1612 if (enable_worker_tracking) {
1613 // TODO implement some kind of switch to have the possibily to use it
1614 *enable_worker_tracking = FALSE;
1617 mono_lazy_initialize (&status, initialize);
1621 ves_icall_System_Threading_ThreadPool_NotifyWorkItemComplete (void)
1623 ThreadPoolCounter counter;
1625 if (mono_domain_is_unloading (mono_domain_get ()) || mono_runtime_is_shutting_down ())
1628 heuristic_notify_work_completed ();
1630 if (heuristic_should_adjust ())
1631 heuristic_adjust ();
1633 counter.as_gint64 = COUNTER_READ ();
1634 return counter._.working <= counter._.max_working;
1638 ves_icall_System_Threading_ThreadPool_NotifyWorkItemProgressNative (void)
1640 heuristic_notify_work_completed ();
1642 if (heuristic_should_adjust ())
1643 heuristic_adjust ();
1647 ves_icall_System_Threading_ThreadPool_ReportThreadStatus (MonoBoolean is_working)
1651 mono_error_set_not_implemented (&error, "");
1652 mono_error_set_pending_exception (&error);
1656 ves_icall_System_Threading_ThreadPool_RequestWorkerThread (void)
1658 return worker_request (mono_domain_get ());
1661 MonoBoolean G_GNUC_UNUSED
1662 ves_icall_System_Threading_ThreadPool_PostQueuedCompletionStatus (MonoNativeOverlapped *native_overlapped)
1664 /* This copy the behavior of the current Mono implementation */
1666 mono_error_set_not_implemented (&error, "");
1667 mono_error_set_pending_exception (&error);
1671 MonoBoolean G_GNUC_UNUSED
1672 ves_icall_System_Threading_ThreadPool_BindIOCompletionCallbackNative (gpointer file_handle)
1674 /* This copy the behavior of the current Mono implementation */
1678 MonoBoolean G_GNUC_UNUSED
1679 ves_icall_System_Threading_ThreadPool_IsThreadPoolHosted (void)