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/utils/atomic.h>
37 #include <mono/utils/mono-compiler.h>
38 #include <mono/utils/mono-complex.h>
39 #include <mono/utils/mono-lazy-init.h>
40 #include <mono/utils/mono-logger.h>
41 #include <mono/utils/mono-logger-internals.h>
42 #include <mono/utils/mono-proclib.h>
43 #include <mono/utils/mono-threads.h>
44 #include <mono/utils/mono-time.h>
45 #include <mono/utils/mono-rand.h>
47 #define CPU_USAGE_LOW 80
48 #define CPU_USAGE_HIGH 95
50 #define MONITOR_INTERVAL 500 // ms
51 #define MONITOR_MINIMAL_LIFETIME 60 * 1000 // ms
53 #define WORKER_CREATION_MAX_PER_SEC 10
55 /* The exponent to apply to the gain. 1.0 means to use linear gain,
56 * higher values will enhance large moves and damp small ones.
58 #define HILL_CLIMBING_GAIN_EXPONENT 2.0
60 /* The 'cost' of a thread. 0 means drive for increased throughput regardless
61 * of thread count, higher values bias more against higher thread counts.
63 #define HILL_CLIMBING_BIAS 0.15
65 #define HILL_CLIMBING_WAVE_PERIOD 4
66 #define HILL_CLIMBING_MAX_WAVE_MAGNITUDE 20
67 #define HILL_CLIMBING_WAVE_MAGNITUDE_MULTIPLIER 1.0
68 #define HILL_CLIMBING_WAVE_HISTORY_SIZE 8
69 #define HILL_CLIMBING_TARGET_SIGNAL_TO_NOISE_RATIO 3.0
70 #define HILL_CLIMBING_MAX_CHANGE_PER_SECOND 4
71 #define HILL_CLIMBING_MAX_CHANGE_PER_SAMPLE 20
72 #define HILL_CLIMBING_SAMPLE_INTERVAL_LOW 10
73 #define HILL_CLIMBING_SAMPLE_INTERVAL_HIGH 200
74 #define HILL_CLIMBING_ERROR_SMOOTHING_FACTOR 0.01
75 #define HILL_CLIMBING_MAX_SAMPLE_ERROR_PERCENT 0.15
79 gint16 max_working; /* determined by heuristic */
80 gint16 active; /* executing worker_thread */
81 gint16 working; /* actively executing worker_thread, not parked */
82 gint16 parked; /* parked */
89 gint32 outstanding_request;
92 typedef MonoInternalThread ThreadPoolWorkingThread;
96 gint32 samples_to_measure;
97 gdouble target_throughput_ratio;
98 gdouble target_signal_to_noise_ratio;
99 gdouble max_change_per_second;
100 gdouble max_change_per_sample;
101 gint32 max_thread_wave_magnitude;
102 gint32 sample_interval_low;
103 gdouble thread_magnitude_multiplier;
104 gint32 sample_interval_high;
105 gdouble throughput_error_smoothing_factor;
106 gdouble gain_exponent;
107 gdouble max_sample_error;
109 gdouble current_control_setting;
110 gint64 total_samples;
111 gint16 last_thread_count;
112 gdouble elapsed_since_last_change;
113 gdouble completions_since_last_change;
115 gdouble average_throughput_noise;
118 gdouble *thread_counts;
120 guint32 current_sample_interval;
121 gpointer random_interval_generator;
123 gint32 accumulated_completion_count;
124 gdouble accumulated_sample_duration;
125 } ThreadPoolHillClimbing;
128 ThreadPoolCounter counters;
130 GPtrArray *domains; // ThreadPoolDomain* []
131 MonoCoopMutex domains_lock;
133 GPtrArray *working_threads; // ThreadPoolWorkingThread* []
134 gint32 parked_threads_count;
135 MonoCoopCond parked_threads_cond;
136 MonoCoopMutex active_threads_lock; /* protect access to working_threads and parked_threads */
138 guint32 worker_creation_current_second;
139 guint32 worker_creation_current_count;
140 MonoCoopMutex worker_creation_lock;
142 gint32 heuristic_completions;
143 gint64 heuristic_sample_start;
144 gint64 heuristic_last_dequeue; // ms
145 gint64 heuristic_last_adjustment; // ms
146 gint64 heuristic_adjustment_interval; // ms
147 ThreadPoolHillClimbing heuristic_hill_climbing;
148 MonoCoopMutex heuristic_lock;
150 gint32 limit_worker_min;
151 gint32 limit_worker_max;
155 MonoCpuUsageState *cpu_usage_state;
158 /* suspended by the debugger */
164 TRANSITION_INITIALIZING,
165 TRANSITION_RANDOM_MOVE,
166 TRANSITION_CLIMBING_MOVE,
167 TRANSITION_CHANGE_POINT,
168 TRANSITION_STABILIZING,
169 TRANSITION_STARVATION,
170 TRANSITION_THREAD_TIMED_OUT,
171 TRANSITION_UNDEFINED,
172 } ThreadPoolHeuristicStateTransition;
174 static mono_lazy_init_t status = MONO_LAZY_INIT_STATUS_NOT_INITIALIZED;
177 MONITOR_STATUS_REQUESTED,
178 MONITOR_STATUS_WAITING_FOR_REQUEST,
179 MONITOR_STATUS_NOT_RUNNING,
182 static gint32 monitor_status = MONITOR_STATUS_NOT_RUNNING;
184 static ThreadPool* threadpool;
186 #define COUNTER_CHECK(counter) \
188 g_assert (counter._.max_working > 0); \
189 g_assert (counter._.working >= 0); \
190 g_assert (counter._.active >= 0); \
193 #define COUNTER_READ() (InterlockedRead64 (&threadpool->counters.as_gint64))
195 #define COUNTER_ATOMIC(var,block) \
197 ThreadPoolCounter __old; \
199 g_assert (threadpool); \
200 __old.as_gint64 = COUNTER_READ (); \
203 COUNTER_CHECK (var); \
204 } while (InterlockedCompareExchange64 (&threadpool->counters.as_gint64, (var).as_gint64, __old.as_gint64) != __old.as_gint64); \
207 #define COUNTER_TRY_ATOMIC(res,var,block) \
209 ThreadPoolCounter __old; \
211 g_assert (threadpool); \
212 __old.as_gint64 = COUNTER_READ (); \
216 COUNTER_CHECK (var); \
217 (res) = InterlockedCompareExchange64 (&threadpool->counters.as_gint64, (var).as_gint64, __old.as_gint64) == __old.as_gint64; \
225 return mono_rand_init (NULL, 0);
229 rand_next (gpointer *handle, guint32 min, guint32 max)
233 mono_rand_try_get_uint32 (handle, &val, min, max, &error);
234 // FIXME handle error
235 mono_error_assert_ok (&error);
240 rand_free (gpointer handle)
242 mono_rand_close (handle);
248 ThreadPoolHillClimbing *hc;
249 const char *threads_per_cpu_env;
250 gint threads_per_cpu;
253 g_assert (!threadpool);
254 threadpool = g_new0 (ThreadPool, 1);
255 g_assert (threadpool);
257 threadpool->domains = g_ptr_array_new ();
258 mono_coop_mutex_init (&threadpool->domains_lock);
260 threadpool->parked_threads_count = 0;
261 mono_coop_cond_init (&threadpool->parked_threads_cond);
262 threadpool->working_threads = g_ptr_array_new ();
263 mono_coop_mutex_init (&threadpool->active_threads_lock);
265 threadpool->worker_creation_current_second = -1;
266 mono_coop_mutex_init (&threadpool->worker_creation_lock);
268 threadpool->heuristic_adjustment_interval = 10;
269 mono_coop_mutex_init (&threadpool->heuristic_lock);
273 hc = &threadpool->heuristic_hill_climbing;
275 hc->wave_period = HILL_CLIMBING_WAVE_PERIOD;
276 hc->max_thread_wave_magnitude = HILL_CLIMBING_MAX_WAVE_MAGNITUDE;
277 hc->thread_magnitude_multiplier = (gdouble) HILL_CLIMBING_WAVE_MAGNITUDE_MULTIPLIER;
278 hc->samples_to_measure = hc->wave_period * HILL_CLIMBING_WAVE_HISTORY_SIZE;
279 hc->target_throughput_ratio = (gdouble) HILL_CLIMBING_BIAS;
280 hc->target_signal_to_noise_ratio = (gdouble) HILL_CLIMBING_TARGET_SIGNAL_TO_NOISE_RATIO;
281 hc->max_change_per_second = (gdouble) HILL_CLIMBING_MAX_CHANGE_PER_SECOND;
282 hc->max_change_per_sample = (gdouble) HILL_CLIMBING_MAX_CHANGE_PER_SAMPLE;
283 hc->sample_interval_low = HILL_CLIMBING_SAMPLE_INTERVAL_LOW;
284 hc->sample_interval_high = HILL_CLIMBING_SAMPLE_INTERVAL_HIGH;
285 hc->throughput_error_smoothing_factor = (gdouble) HILL_CLIMBING_ERROR_SMOOTHING_FACTOR;
286 hc->gain_exponent = (gdouble) HILL_CLIMBING_GAIN_EXPONENT;
287 hc->max_sample_error = (gdouble) HILL_CLIMBING_MAX_SAMPLE_ERROR_PERCENT;
288 hc->current_control_setting = 0;
289 hc->total_samples = 0;
290 hc->last_thread_count = 0;
291 hc->average_throughput_noise = 0;
292 hc->elapsed_since_last_change = 0;
293 hc->accumulated_completion_count = 0;
294 hc->accumulated_sample_duration = 0;
295 hc->samples = g_new0 (gdouble, hc->samples_to_measure);
296 hc->thread_counts = g_new0 (gdouble, hc->samples_to_measure);
297 hc->random_interval_generator = rand_create ();
298 hc->current_sample_interval = rand_next (&hc->random_interval_generator, hc->sample_interval_low, hc->sample_interval_high);
300 if (!(threads_per_cpu_env = g_getenv ("MONO_THREADS_PER_CPU")))
303 threads_per_cpu = CLAMP (atoi (threads_per_cpu_env), 1, 50);
305 threads_count = mono_cpu_count () * threads_per_cpu;
307 threadpool->limit_worker_min = threadpool->limit_io_min = threads_count;
309 #if defined (PLATFORM_ANDROID) || defined (HOST_IOS)
310 threadpool->limit_worker_max = threadpool->limit_io_max = CLAMP (threads_count * 100, MIN (threads_count, 200), MAX (threads_count, 200));
312 threadpool->limit_worker_max = threadpool->limit_io_max = threads_count * 100;
315 threadpool->counters._.max_working = threadpool->limit_worker_min;
317 threadpool->cpu_usage_state = g_new0 (MonoCpuUsageState, 1);
319 threadpool->suspended = FALSE;
322 static void worker_kill (ThreadPoolWorkingThread *thread);
329 /* we make the assumption along the code that we are
330 * cleaning up only if the runtime is shutting down */
331 g_assert (mono_runtime_is_shutting_down ());
333 while (monitor_status != MONITOR_STATUS_NOT_RUNNING)
334 mono_thread_info_sleep (1, NULL);
336 mono_coop_mutex_lock (&threadpool->active_threads_lock);
338 /* stop all threadpool->working_threads */
339 for (i = 0; i < threadpool->working_threads->len; ++i)
340 worker_kill ((ThreadPoolWorkingThread*) g_ptr_array_index (threadpool->working_threads, i));
342 /* unpark all threadpool->parked_threads */
343 mono_coop_cond_broadcast (&threadpool->parked_threads_cond);
345 mono_coop_mutex_unlock (&threadpool->active_threads_lock);
349 mono_threadpool_ms_enqueue_work_item (MonoDomain *domain, MonoObject *work_item, MonoError *error)
351 static MonoClass *threadpool_class = NULL;
352 static MonoMethod *unsafe_queue_custom_work_item_method = NULL;
353 MonoDomain *current_domain;
357 mono_error_init (error);
358 g_assert (work_item);
360 if (!threadpool_class)
361 threadpool_class = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "ThreadPool");
363 if (!unsafe_queue_custom_work_item_method)
364 unsafe_queue_custom_work_item_method = mono_class_get_method_from_name (threadpool_class, "UnsafeQueueCustomWorkItem", 2);
365 g_assert (unsafe_queue_custom_work_item_method);
369 args [0] = (gpointer) work_item;
370 args [1] = (gpointer) &f;
372 current_domain = mono_domain_get ();
373 if (current_domain == domain) {
374 mono_runtime_invoke_checked (unsafe_queue_custom_work_item_method, NULL, args, error);
375 return_val_if_nok (error, FALSE);
377 mono_thread_push_appdomain_ref (domain);
378 if (mono_domain_set (domain, FALSE)) {
379 mono_runtime_invoke_checked (unsafe_queue_custom_work_item_method, NULL, args, error);
380 if (!is_ok (error)) {
381 mono_thread_pop_appdomain_ref ();
384 mono_domain_set (current_domain, TRUE);
386 mono_thread_pop_appdomain_ref ();
391 /* LOCKING: threadpool->domains_lock must be held */
393 domain_add (ThreadPoolDomain *tpdomain)
399 len = threadpool->domains->len;
400 for (i = 0; i < len; ++i) {
401 if (g_ptr_array_index (threadpool->domains, i) == tpdomain)
406 g_ptr_array_add (threadpool->domains, tpdomain);
409 /* LOCKING: threadpool->domains_lock must be held */
411 domain_remove (ThreadPoolDomain *tpdomain)
414 return g_ptr_array_remove (threadpool->domains, tpdomain);
417 /* LOCKING: threadpool->domains_lock must be held */
418 static ThreadPoolDomain *
419 domain_get (MonoDomain *domain, gboolean create)
421 ThreadPoolDomain *tpdomain = NULL;
426 for (i = 0; i < threadpool->domains->len; ++i) {
427 tpdomain = (ThreadPoolDomain *)g_ptr_array_index (threadpool->domains, i);
428 if (tpdomain->domain == domain)
433 tpdomain = g_new0 (ThreadPoolDomain, 1);
434 tpdomain->domain = domain;
435 domain_add (tpdomain);
442 domain_free (ThreadPoolDomain *tpdomain)
447 /* LOCKING: threadpool->domains_lock must be held */
449 domain_any_has_request (void)
453 for (i = 0; i < threadpool->domains->len; ++i) {
454 ThreadPoolDomain *tmp = (ThreadPoolDomain *)g_ptr_array_index (threadpool->domains, i);
455 if (tmp->outstanding_request > 0)
462 /* LOCKING: threadpool->domains_lock must be held */
463 static ThreadPoolDomain *
464 domain_get_next (ThreadPoolDomain *current)
466 ThreadPoolDomain *tpdomain = NULL;
469 len = threadpool->domains->len;
471 guint i, current_idx = -1;
473 for (i = 0; i < len; ++i) {
474 if (current == g_ptr_array_index (threadpool->domains, i)) {
479 g_assert (current_idx >= 0);
481 for (i = current_idx + 1; i < len + current_idx + 1; ++i) {
482 ThreadPoolDomain *tmp = (ThreadPoolDomain *)g_ptr_array_index (threadpool->domains, i % len);
483 if (tmp->outstanding_request > 0) {
494 worker_wait_interrupt (gpointer data)
496 mono_coop_mutex_lock (&threadpool->active_threads_lock);
497 mono_coop_cond_signal (&threadpool->parked_threads_cond);
498 mono_coop_mutex_unlock (&threadpool->active_threads_lock);
501 /* return TRUE if timeout, FALSE otherwise (worker unpark or interrupt) */
505 gboolean timeout = FALSE;
507 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] current worker parking", mono_native_thread_id_get ());
509 mono_gc_set_skip_thread (TRUE);
511 mono_coop_mutex_lock (&threadpool->active_threads_lock);
513 if (!mono_runtime_is_shutting_down ()) {
514 static gpointer rand_handle = NULL;
515 MonoInternalThread *thread_internal;
516 gboolean interrupted = FALSE;
519 rand_handle = rand_create ();
520 g_assert (rand_handle);
522 thread_internal = mono_thread_internal_current ();
523 g_assert (thread_internal);
525 threadpool->parked_threads_count += 1;
526 g_ptr_array_remove_fast (threadpool->working_threads, thread_internal);
528 mono_thread_info_install_interrupt (worker_wait_interrupt, NULL, &interrupted);
532 if (mono_coop_cond_timedwait (&threadpool->parked_threads_cond, &threadpool->active_threads_lock, rand_next (&rand_handle, 5 * 1000, 60 * 1000)) != 0)
535 mono_thread_info_uninstall_interrupt (&interrupted);
538 g_ptr_array_add (threadpool->working_threads, thread_internal);
539 threadpool->parked_threads_count -= 1;
542 mono_coop_mutex_unlock (&threadpool->active_threads_lock);
544 mono_gc_set_skip_thread (FALSE);
546 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] current worker unparking, timeout? %s", mono_native_thread_id_get (), timeout ? "yes" : "no");
552 worker_try_unpark (void)
554 gboolean res = FALSE;
556 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try unpark worker", mono_native_thread_id_get ());
558 mono_coop_mutex_lock (&threadpool->active_threads_lock);
559 if (threadpool->parked_threads_count > 0) {
560 mono_coop_cond_signal (&threadpool->parked_threads_cond);
563 mono_coop_mutex_unlock (&threadpool->active_threads_lock);
565 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try unpark worker, success? %s", mono_native_thread_id_get (), res ? "yes" : "no");
571 worker_kill (ThreadPoolWorkingThread *thread)
573 if (thread == mono_thread_internal_current ())
576 mono_thread_internal_stop ((MonoInternalThread*) thread);
580 worker_thread (gpointer data)
583 MonoInternalThread *thread;
584 ThreadPoolDomain *tpdomain, *previous_tpdomain;
585 ThreadPoolCounter counter;
586 gboolean retire = FALSE;
588 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_THREADPOOL, "[%p] worker starting", mono_native_thread_id_get ());
590 g_assert (threadpool);
592 thread = mono_thread_internal_current ();
595 mono_thread_set_name_internal (thread, mono_string_new (mono_get_root_domain (), "Threadpool worker"), FALSE, &error);
596 mono_error_assert_ok (&error);
598 mono_coop_mutex_lock (&threadpool->active_threads_lock);
599 g_ptr_array_add (threadpool->working_threads, thread);
600 mono_coop_mutex_unlock (&threadpool->active_threads_lock);
602 previous_tpdomain = NULL;
604 mono_coop_mutex_lock (&threadpool->domains_lock);
606 while (!mono_runtime_is_shutting_down ()) {
609 if ((thread->state & (ThreadState_StopRequested | ThreadState_SuspendRequested)) != 0) {
610 mono_coop_mutex_unlock (&threadpool->domains_lock);
611 mono_thread_interruption_checkpoint ();
612 mono_coop_mutex_lock (&threadpool->domains_lock);
615 if (retire || !(tpdomain = domain_get_next (previous_tpdomain))) {
618 COUNTER_ATOMIC (counter, {
619 counter._.working --;
623 mono_coop_mutex_unlock (&threadpool->domains_lock);
624 timeout = worker_park ();
625 mono_coop_mutex_lock (&threadpool->domains_lock);
627 COUNTER_ATOMIC (counter, {
628 counter._.working ++;
641 tpdomain->outstanding_request --;
642 g_assert (tpdomain->outstanding_request >= 0);
644 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] worker running in domain %p",
645 mono_native_thread_id_get (), tpdomain->domain, tpdomain->outstanding_request);
647 g_assert (tpdomain->domain);
648 g_assert (tpdomain->domain->threadpool_jobs >= 0);
649 tpdomain->domain->threadpool_jobs ++;
651 mono_coop_mutex_unlock (&threadpool->domains_lock);
653 mono_thread_push_appdomain_ref (tpdomain->domain);
654 if (mono_domain_set (tpdomain->domain, FALSE)) {
655 MonoObject *exc = NULL, *res;
657 res = mono_runtime_try_invoke (mono_defaults.threadpool_perform_wait_callback_method, NULL, NULL, &exc, &error);
658 if (exc || !mono_error_ok(&error)) {
660 exc = (MonoObject *) mono_error_convert_to_exception (&error);
662 mono_error_cleanup (&error);
663 mono_thread_internal_unhandled_exception (exc);
664 } else if (res && *(MonoBoolean*) mono_object_unbox (res) == FALSE)
667 mono_thread_clr_state (thread, (MonoThreadState)~ThreadState_Background);
668 if (!mono_thread_test_state (thread , ThreadState_Background))
669 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
671 mono_domain_set (mono_get_root_domain (), TRUE);
673 mono_thread_pop_appdomain_ref ();
675 mono_coop_mutex_lock (&threadpool->domains_lock);
677 tpdomain->domain->threadpool_jobs --;
678 g_assert (tpdomain->domain->threadpool_jobs >= 0);
680 if (tpdomain->domain->threadpool_jobs == 0 && mono_domain_is_unloading (tpdomain->domain)) {
681 gboolean removed = domain_remove (tpdomain);
683 if (tpdomain->domain->cleanup_semaphore)
684 ReleaseSemaphore (tpdomain->domain->cleanup_semaphore, 1, NULL);
685 domain_free (tpdomain);
689 previous_tpdomain = tpdomain;
692 mono_coop_mutex_unlock (&threadpool->domains_lock);
694 mono_coop_mutex_lock (&threadpool->active_threads_lock);
695 g_ptr_array_remove_fast (threadpool->working_threads, thread);
696 mono_coop_mutex_unlock (&threadpool->active_threads_lock);
698 COUNTER_ATOMIC (counter, {
703 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_THREADPOOL, "[%p] worker finishing", mono_native_thread_id_get ());
707 worker_try_create (void)
709 ThreadPoolCounter counter;
710 MonoInternalThread *thread;
713 mono_coop_mutex_lock (&threadpool->worker_creation_lock);
715 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker", mono_native_thread_id_get ());
717 if ((now = mono_100ns_ticks () / 10 / 1000 / 1000) == 0) {
718 g_warning ("failed to get 100ns ticks");
720 if (threadpool->worker_creation_current_second != now) {
721 threadpool->worker_creation_current_second = now;
722 threadpool->worker_creation_current_count = 0;
724 g_assert (threadpool->worker_creation_current_count <= WORKER_CREATION_MAX_PER_SEC);
725 if (threadpool->worker_creation_current_count == WORKER_CREATION_MAX_PER_SEC) {
726 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",
727 mono_native_thread_id_get (), threadpool->worker_creation_current_count);
728 mono_coop_mutex_unlock (&threadpool->worker_creation_lock);
734 COUNTER_ATOMIC (counter, {
735 if (counter._.working >= counter._.max_working) {
736 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker, failed: maximum number of working threads reached",
737 mono_native_thread_id_get ());
738 mono_coop_mutex_unlock (&threadpool->worker_creation_lock);
741 counter._.working ++;
746 if ((thread = mono_thread_create_internal (mono_get_root_domain (), worker_thread, NULL, TRUE, 0, &error)) != NULL) {
747 threadpool->worker_creation_current_count += 1;
749 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);
750 mono_coop_mutex_unlock (&threadpool->worker_creation_lock);
754 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));
755 mono_error_cleanup (&error);
757 COUNTER_ATOMIC (counter, {
758 counter._.working --;
762 mono_coop_mutex_unlock (&threadpool->worker_creation_lock);
766 static void monitor_ensure_running (void);
769 worker_request (MonoDomain *domain)
771 ThreadPoolDomain *tpdomain;
774 g_assert (threadpool);
776 if (mono_runtime_is_shutting_down ())
779 mono_coop_mutex_lock (&threadpool->domains_lock);
781 /* synchronize check with worker_thread */
782 if (mono_domain_is_unloading (domain)) {
783 mono_coop_mutex_unlock (&threadpool->domains_lock);
787 tpdomain = domain_get (domain, TRUE);
789 tpdomain->outstanding_request ++;
791 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] request worker, domain = %p, outstanding_request = %d",
792 mono_native_thread_id_get (), tpdomain->domain, tpdomain->outstanding_request);
794 mono_coop_mutex_unlock (&threadpool->domains_lock);
796 if (threadpool->suspended)
799 monitor_ensure_running ();
801 if (worker_try_unpark ()) {
802 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] request worker, unparked", mono_native_thread_id_get ());
806 if (worker_try_create ()) {
807 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] request worker, created", mono_native_thread_id_get ());
811 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] request worker, failed", mono_native_thread_id_get ());
816 monitor_should_keep_running (void)
818 static gint64 last_should_keep_running = -1;
820 g_assert (monitor_status == MONITOR_STATUS_WAITING_FOR_REQUEST || monitor_status == MONITOR_STATUS_REQUESTED);
822 if (InterlockedExchange (&monitor_status, MONITOR_STATUS_WAITING_FOR_REQUEST) == MONITOR_STATUS_WAITING_FOR_REQUEST) {
823 gboolean should_keep_running = TRUE, force_should_keep_running = FALSE;
825 if (mono_runtime_is_shutting_down ()) {
826 should_keep_running = FALSE;
828 mono_coop_mutex_lock (&threadpool->domains_lock);
829 if (!domain_any_has_request ())
830 should_keep_running = FALSE;
831 mono_coop_mutex_unlock (&threadpool->domains_lock);
833 if (!should_keep_running) {
834 if (last_should_keep_running == -1 || mono_100ns_ticks () - last_should_keep_running < MONITOR_MINIMAL_LIFETIME * 1000 * 10) {
835 should_keep_running = force_should_keep_running = TRUE;
840 if (should_keep_running) {
841 if (last_should_keep_running == -1 || !force_should_keep_running)
842 last_should_keep_running = mono_100ns_ticks ();
844 last_should_keep_running = -1;
845 if (InterlockedCompareExchange (&monitor_status, MONITOR_STATUS_NOT_RUNNING, MONITOR_STATUS_WAITING_FOR_REQUEST) == MONITOR_STATUS_WAITING_FOR_REQUEST)
850 g_assert (monitor_status == MONITOR_STATUS_WAITING_FOR_REQUEST || monitor_status == MONITOR_STATUS_REQUESTED);
856 monitor_sufficient_delay_since_last_dequeue (void)
860 g_assert (threadpool);
862 if (threadpool->cpu_usage < CPU_USAGE_LOW) {
863 threshold = MONITOR_INTERVAL;
865 ThreadPoolCounter counter;
866 counter.as_gint64 = COUNTER_READ();
867 threshold = counter._.max_working * MONITOR_INTERVAL * 2;
870 return mono_msec_ticks () >= threadpool->heuristic_last_dequeue + threshold;
873 static void hill_climbing_force_change (gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition);
876 monitor_thread (void)
878 MonoInternalThread *current_thread = mono_thread_internal_current ();
881 mono_cpu_usage (threadpool->cpu_usage_state);
883 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, started", mono_native_thread_id_get ());
886 ThreadPoolCounter counter;
887 gboolean limit_worker_max_reached;
888 gint32 interval_left = MONITOR_INTERVAL;
889 gint32 awake = 0; /* number of spurious awakes we tolerate before doing a round of rebalancing */
891 g_assert (monitor_status != MONITOR_STATUS_NOT_RUNNING);
893 mono_gc_set_skip_thread (TRUE);
897 gboolean alerted = FALSE;
899 if (mono_runtime_is_shutting_down ())
902 ts = mono_msec_ticks ();
903 if (mono_thread_info_sleep (interval_left, &alerted) == 0)
905 interval_left -= mono_msec_ticks () - ts;
907 mono_gc_set_skip_thread (FALSE);
908 if ((current_thread->state & (ThreadState_StopRequested | ThreadState_SuspendRequested)) != 0)
909 mono_thread_interruption_checkpoint ();
910 mono_gc_set_skip_thread (TRUE);
911 } while (interval_left > 0 && ++awake < 10);
913 mono_gc_set_skip_thread (FALSE);
915 if (threadpool->suspended)
918 if (mono_runtime_is_shutting_down ())
921 mono_coop_mutex_lock (&threadpool->domains_lock);
922 if (!domain_any_has_request ()) {
923 mono_coop_mutex_unlock (&threadpool->domains_lock);
926 mono_coop_mutex_unlock (&threadpool->domains_lock);
928 threadpool->cpu_usage = mono_cpu_usage (threadpool->cpu_usage_state);
930 if (!monitor_sufficient_delay_since_last_dequeue ())
933 limit_worker_max_reached = FALSE;
935 COUNTER_ATOMIC (counter, {
936 if (counter._.max_working >= threadpool->limit_worker_max) {
937 limit_worker_max_reached = TRUE;
940 counter._.max_working ++;
943 if (limit_worker_max_reached)
946 hill_climbing_force_change (counter._.max_working, TRANSITION_STARVATION);
948 for (i = 0; i < 5; ++i) {
949 if (mono_runtime_is_shutting_down ())
952 if (worker_try_unpark ()) {
953 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, unparked", mono_native_thread_id_get ());
957 if (worker_try_create ()) {
958 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, created", mono_native_thread_id_get ());
962 } while (monitor_should_keep_running ());
964 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, finished", mono_native_thread_id_get ());
968 monitor_ensure_running (void)
972 switch (monitor_status) {
973 case MONITOR_STATUS_REQUESTED:
975 case MONITOR_STATUS_WAITING_FOR_REQUEST:
976 InterlockedCompareExchange (&monitor_status, MONITOR_STATUS_REQUESTED, MONITOR_STATUS_WAITING_FOR_REQUEST);
978 case MONITOR_STATUS_NOT_RUNNING:
979 if (mono_runtime_is_shutting_down ())
981 if (InterlockedCompareExchange (&monitor_status, MONITOR_STATUS_REQUESTED, MONITOR_STATUS_NOT_RUNNING) == MONITOR_STATUS_NOT_RUNNING) {
982 if (!mono_thread_create_internal (mono_get_root_domain (), monitor_thread, NULL, TRUE, SMALL_STACK, &error)) {
983 monitor_status = MONITOR_STATUS_NOT_RUNNING;
984 mono_error_cleanup (&error);
989 default: g_assert_not_reached ();
995 hill_climbing_change_thread_count (gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition)
997 ThreadPoolHillClimbing *hc;
999 g_assert (threadpool);
1001 hc = &threadpool->heuristic_hill_climbing;
1003 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);
1005 hc->last_thread_count = new_thread_count;
1006 hc->current_sample_interval = rand_next (&hc->random_interval_generator, hc->sample_interval_low, hc->sample_interval_high);
1007 hc->elapsed_since_last_change = 0;
1008 hc->completions_since_last_change = 0;
1012 hill_climbing_force_change (gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition)
1014 ThreadPoolHillClimbing *hc;
1016 g_assert (threadpool);
1018 hc = &threadpool->heuristic_hill_climbing;
1020 if (new_thread_count != hc->last_thread_count) {
1021 hc->current_control_setting += new_thread_count - hc->last_thread_count;
1022 hill_climbing_change_thread_count (new_thread_count, transition);
1026 static double_complex
1027 hill_climbing_get_wave_component (gdouble *samples, guint sample_count, gdouble period)
1029 ThreadPoolHillClimbing *hc;
1030 gdouble w, cosine, sine, coeff, q0, q1, q2;
1033 g_assert (threadpool);
1034 g_assert (sample_count >= period);
1035 g_assert (period >= 2);
1037 hc = &threadpool->heuristic_hill_climbing;
1039 w = 2.0 * M_PI / period;
1042 coeff = 2.0 * cosine;
1045 for (i = 0; i < sample_count; ++i) {
1046 q0 = coeff * q1 - q2 + samples [(hc->total_samples - sample_count + i) % hc->samples_to_measure];
1051 return mono_double_complex_scalar_div (mono_double_complex_make (q1 - q2 * cosine, (q2 * sine)), ((gdouble)sample_count));
1055 hill_climbing_update (gint16 current_thread_count, guint32 sample_duration, gint32 completions, gint64 *adjustment_interval)
1057 ThreadPoolHillClimbing *hc;
1058 ThreadPoolHeuristicStateTransition transition;
1060 gdouble throughput_error_estimate;
1066 gint new_thread_wave_magnitude;
1067 gint new_thread_count;
1068 double_complex thread_wave_component;
1069 double_complex throughput_wave_component;
1070 double_complex ratio;
1072 g_assert (threadpool);
1073 g_assert (adjustment_interval);
1075 hc = &threadpool->heuristic_hill_climbing;
1077 /* If someone changed the thread count without telling us, update our records accordingly. */
1078 if (current_thread_count != hc->last_thread_count)
1079 hill_climbing_force_change (current_thread_count, TRANSITION_INITIALIZING);
1081 /* Update the cumulative stats for this thread count */
1082 hc->elapsed_since_last_change += sample_duration;
1083 hc->completions_since_last_change += completions;
1085 /* Add in any data we've already collected about this sample */
1086 sample_duration += hc->accumulated_sample_duration;
1087 completions += hc->accumulated_completion_count;
1089 /* We need to make sure we're collecting reasonably accurate data. Since we're just counting the end
1090 * of each work item, we are goinng to be missing some data about what really happened during the
1091 * sample interval. The count produced by each thread includes an initial work item that may have
1092 * started well before the start of the interval, and each thread may have been running some new
1093 * work item for some time before the end of the interval, which did not yet get counted. So
1094 * our count is going to be off by +/- threadCount workitems.
1096 * The exception is that the thread that reported to us last time definitely wasn't running any work
1097 * at that time, and the thread that's reporting now definitely isn't running a work item now. So
1098 * we really only need to consider threadCount-1 threads.
1100 * Thus the percent error in our count is +/- (threadCount-1)/numCompletions.
1102 * We cannot rely on the frequency-domain analysis we'll be doing later to filter out this error, because
1103 * of the way it accumulates over time. If this sample is off by, say, 33% in the negative direction,
1104 * then the next one likely will be too. The one after that will include the sum of the completions
1105 * we missed in the previous samples, and so will be 33% positive. So every three samples we'll have
1106 * two "low" samples and one "high" sample. This will appear as periodic variation right in the frequency
1107 * range we're targeting, which will not be filtered by the frequency-domain translation. */
1108 if (hc->total_samples > 0 && ((current_thread_count - 1.0) / completions) >= hc->max_sample_error) {
1109 /* Not accurate enough yet. Let's accumulate the data so
1110 * far, and tell the ThreadPool to collect a little more. */
1111 hc->accumulated_sample_duration = sample_duration;
1112 hc->accumulated_completion_count = completions;
1113 *adjustment_interval = 10;
1114 return current_thread_count;
1117 /* We've got enouugh data for our sample; reset our accumulators for next time. */
1118 hc->accumulated_sample_duration = 0;
1119 hc->accumulated_completion_count = 0;
1121 /* Add the current thread count and throughput sample to our history. */
1122 throughput = ((gdouble) completions) / sample_duration;
1124 sample_index = hc->total_samples % hc->samples_to_measure;
1125 hc->samples [sample_index] = throughput;
1126 hc->thread_counts [sample_index] = current_thread_count;
1127 hc->total_samples ++;
1129 /* Set up defaults for our metrics. */
1130 thread_wave_component = mono_double_complex_make(0, 0);
1131 throughput_wave_component = mono_double_complex_make(0, 0);
1132 throughput_error_estimate = 0;
1133 ratio = mono_double_complex_make(0, 0);
1136 transition = TRANSITION_WARMUP;
1138 /* How many samples will we use? It must be at least the three wave periods we're looking for, and it must also
1139 * be a whole multiple of the primary wave's period; otherwise the frequency we're looking for will fall between
1140 * two frequency bands in the Fourier analysis, and we won't be able to measure it accurately. */
1141 sample_count = ((gint) MIN (hc->total_samples - 1, hc->samples_to_measure) / hc->wave_period) * hc->wave_period;
1143 if (sample_count > hc->wave_period) {
1145 gdouble average_throughput;
1146 gdouble average_thread_count;
1147 gdouble sample_sum = 0;
1148 gdouble thread_sum = 0;
1150 /* Average the throughput and thread count samples, so we can scale the wave magnitudes later. */
1151 for (i = 0; i < sample_count; ++i) {
1152 guint j = (hc->total_samples - sample_count + i) % hc->samples_to_measure;
1153 sample_sum += hc->samples [j];
1154 thread_sum += hc->thread_counts [j];
1157 average_throughput = sample_sum / sample_count;
1158 average_thread_count = thread_sum / sample_count;
1160 if (average_throughput > 0 && average_thread_count > 0) {
1161 gdouble noise_for_confidence, adjacent_period_1, adjacent_period_2;
1163 /* Calculate the periods of the adjacent frequency bands we'll be using to
1164 * measure noise levels. We want the two adjacent Fourier frequency bands. */
1165 adjacent_period_1 = sample_count / (((gdouble) sample_count) / ((gdouble) hc->wave_period) + 1);
1166 adjacent_period_2 = sample_count / (((gdouble) sample_count) / ((gdouble) hc->wave_period) - 1);
1168 /* Get the the three different frequency components of the throughput (scaled by average
1169 * throughput). Our "error" estimate (the amount of noise that might be present in the
1170 * frequency band we're really interested in) is the average of the adjacent bands. */
1171 throughput_wave_component = mono_double_complex_scalar_div (hill_climbing_get_wave_component (hc->samples, sample_count, hc->wave_period), average_throughput);
1172 throughput_error_estimate = cabs (mono_double_complex_scalar_div (hill_climbing_get_wave_component (hc->samples, sample_count, adjacent_period_1), average_throughput));
1174 if (adjacent_period_2 <= sample_count) {
1175 throughput_error_estimate = MAX (throughput_error_estimate, cabs (mono_double_complex_scalar_div (hill_climbing_get_wave_component (
1176 hc->samples, sample_count, adjacent_period_2), average_throughput)));
1179 /* Do the same for the thread counts, so we have something to compare to. We don't
1180 * measure thread count noise, because there is none; these are exact measurements. */
1181 thread_wave_component = mono_double_complex_scalar_div (hill_climbing_get_wave_component (hc->thread_counts, sample_count, hc->wave_period), average_thread_count);
1183 /* Update our moving average of the throughput noise. We'll use this
1184 * later as feedback to determine the new size of the thread wave. */
1185 if (hc->average_throughput_noise == 0) {
1186 hc->average_throughput_noise = throughput_error_estimate;
1188 hc->average_throughput_noise = (hc->throughput_error_smoothing_factor * throughput_error_estimate)
1189 + ((1.0 + hc->throughput_error_smoothing_factor) * hc->average_throughput_noise);
1192 if (cabs (thread_wave_component) > 0) {
1193 /* Adjust the throughput wave so it's centered around the target wave,
1194 * and then calculate the adjusted throughput/thread ratio. */
1195 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);
1196 transition = TRANSITION_CLIMBING_MOVE;
1198 ratio = mono_double_complex_make (0, 0);
1199 transition = TRANSITION_STABILIZING;
1202 noise_for_confidence = MAX (hc->average_throughput_noise, throughput_error_estimate);
1203 if (noise_for_confidence > 0) {
1204 confidence = cabs (thread_wave_component) / noise_for_confidence / hc->target_signal_to_noise_ratio;
1206 /* there is no noise! */
1212 /* We use just the real part of the complex ratio we just calculated. If the throughput signal
1213 * is exactly in phase with the thread signal, this will be the same as taking the magnitude of
1214 * the complex move and moving that far up. If they're 180 degrees out of phase, we'll move
1215 * backward (because this indicates that our changes are having the opposite of the intended effect).
1216 * If they're 90 degrees out of phase, we won't move at all, because we can't tell wether we're
1217 * having a negative or positive effect on throughput. */
1218 move = creal (ratio);
1219 move = CLAMP (move, -1.0, 1.0);
1221 /* Apply our confidence multiplier. */
1222 move *= CLAMP (confidence, -1.0, 1.0);
1224 /* Now apply non-linear gain, such that values around zero are attenuated, while higher values
1225 * are enhanced. This allows us to move quickly if we're far away from the target, but more slowly
1226 * if we're getting close, giving us rapid ramp-up without wild oscillations around the target. */
1227 gain = hc->max_change_per_second * sample_duration;
1228 move = pow (fabs (move), hc->gain_exponent) * (move >= 0.0 ? 1 : -1) * gain;
1229 move = MIN (move, hc->max_change_per_sample);
1231 /* If the result was positive, and CPU is > 95%, refuse the move. */
1232 if (move > 0.0 && threadpool->cpu_usage > CPU_USAGE_HIGH)
1235 /* Apply the move to our control setting. */
1236 hc->current_control_setting += move;
1238 /* Calculate the new thread wave magnitude, which is based on the moving average we've been keeping of the
1239 * throughput error. This average starts at zero, so we'll start with a nice safe little wave at first. */
1240 new_thread_wave_magnitude = (gint)(0.5 + (hc->current_control_setting * hc->average_throughput_noise
1241 * hc->target_signal_to_noise_ratio * hc->thread_magnitude_multiplier * 2.0));
1242 new_thread_wave_magnitude = CLAMP (new_thread_wave_magnitude, 1, hc->max_thread_wave_magnitude);
1244 /* Make sure our control setting is within the ThreadPool's limits. */
1245 hc->current_control_setting = CLAMP (hc->current_control_setting, threadpool->limit_worker_min, threadpool->limit_worker_max - new_thread_wave_magnitude);
1247 /* Calculate the new thread count (control setting + square wave). */
1248 new_thread_count = (gint)(hc->current_control_setting + new_thread_wave_magnitude * ((hc->total_samples / (hc->wave_period / 2)) % 2));
1250 /* Make sure the new thread count doesn't exceed the ThreadPool's limits. */
1251 new_thread_count = CLAMP (new_thread_count, threadpool->limit_worker_min, threadpool->limit_worker_max);
1253 if (new_thread_count != current_thread_count)
1254 hill_climbing_change_thread_count (new_thread_count, transition);
1256 if (creal (ratio) < 0.0 && new_thread_count == threadpool->limit_worker_min)
1257 *adjustment_interval = (gint)(0.5 + hc->current_sample_interval * (10.0 * MAX (-1.0 * creal (ratio), 1.0)));
1259 *adjustment_interval = hc->current_sample_interval;
1261 return new_thread_count;
1265 heuristic_notify_work_completed (void)
1267 g_assert (threadpool);
1269 InterlockedIncrement (&threadpool->heuristic_completions);
1270 threadpool->heuristic_last_dequeue = mono_msec_ticks ();
1274 heuristic_should_adjust (void)
1276 g_assert (threadpool);
1278 if (threadpool->heuristic_last_dequeue > threadpool->heuristic_last_adjustment + threadpool->heuristic_adjustment_interval) {
1279 ThreadPoolCounter counter;
1280 counter.as_gint64 = COUNTER_READ();
1281 if (counter._.working <= counter._.max_working)
1289 heuristic_adjust (void)
1291 g_assert (threadpool);
1293 if (mono_coop_mutex_trylock (&threadpool->heuristic_lock) == 0) {
1294 gint32 completions = InterlockedExchange (&threadpool->heuristic_completions, 0);
1295 gint64 sample_end = mono_msec_ticks ();
1296 gint64 sample_duration = sample_end - threadpool->heuristic_sample_start;
1298 if (sample_duration >= threadpool->heuristic_adjustment_interval / 2) {
1299 ThreadPoolCounter counter;
1300 gint16 new_thread_count;
1302 counter.as_gint64 = COUNTER_READ ();
1303 new_thread_count = hill_climbing_update (counter._.max_working, sample_duration, completions, &threadpool->heuristic_adjustment_interval);
1305 COUNTER_ATOMIC (counter, { counter._.max_working = new_thread_count; });
1307 if (new_thread_count > counter._.max_working)
1308 worker_request (mono_domain_get ());
1310 threadpool->heuristic_sample_start = sample_end;
1311 threadpool->heuristic_last_adjustment = mono_msec_ticks ();
1314 mono_coop_mutex_unlock (&threadpool->heuristic_lock);
1319 mono_threadpool_ms_cleanup (void)
1321 #ifndef DISABLE_SOCKETS
1322 mono_threadpool_ms_io_cleanup ();
1324 mono_lazy_cleanup (&status, cleanup);
1328 mono_threadpool_ms_begin_invoke (MonoDomain *domain, MonoObject *target, MonoMethod *method, gpointer *params, MonoError *error)
1330 static MonoClass *async_call_klass = NULL;
1331 MonoMethodMessage *message;
1332 MonoAsyncResult *async_result;
1333 MonoAsyncCall *async_call;
1334 MonoDelegate *async_callback = NULL;
1335 MonoObject *state = NULL;
1337 if (!async_call_klass)
1338 async_call_klass = mono_class_load_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
1340 mono_lazy_initialize (&status, initialize);
1342 mono_error_init (error);
1344 message = mono_method_call_message_new (method, params, mono_get_delegate_invoke (method->klass), (params != NULL) ? (&async_callback) : NULL, (params != NULL) ? (&state) : NULL);
1346 async_call = (MonoAsyncCall*) mono_object_new_checked (domain, async_call_klass, error);
1347 return_val_if_nok (error, NULL);
1349 MONO_OBJECT_SETREF (async_call, msg, message);
1350 MONO_OBJECT_SETREF (async_call, state, state);
1352 if (async_callback) {
1353 MONO_OBJECT_SETREF (async_call, cb_method, mono_get_delegate_invoke (((MonoObject*) async_callback)->vtable->klass));
1354 MONO_OBJECT_SETREF (async_call, cb_target, async_callback);
1357 async_result = mono_async_result_new (domain, NULL, async_call->state, NULL, (MonoObject*) async_call);
1358 MONO_OBJECT_SETREF (async_result, async_delegate, target);
1360 mono_threadpool_ms_enqueue_work_item (domain, (MonoObject*) async_result, error);
1361 return_val_if_nok (error, NULL);
1363 return async_result;
1367 mono_threadpool_ms_end_invoke (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1373 g_assert (out_args);
1378 /* check if already finished */
1379 mono_monitor_enter ((MonoObject*) ares);
1381 if (ares->endinvoke_called) {
1382 *exc = (MonoObject*) mono_get_exception_invalid_operation (NULL);
1383 mono_monitor_exit ((MonoObject*) ares);
1387 ares->endinvoke_called = 1;
1389 /* wait until we are really finished */
1390 if (ares->completed) {
1391 mono_monitor_exit ((MonoObject *) ares);
1393 gpointer wait_event;
1395 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle*) ares->handle);
1397 wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1398 g_assert(wait_event);
1399 MonoWaitHandle *wait_handle = mono_wait_handle_new (mono_object_domain (ares), wait_event, &error);
1400 mono_error_raise_exception (&error); /* FIXME don't raise here */
1401 MONO_OBJECT_SETREF (ares, handle, (MonoObject*) wait_handle);
1403 mono_monitor_exit ((MonoObject*) ares);
1405 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
1409 ac = (MonoAsyncCall*) ares->object_data;
1412 *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1413 *out_args = ac->out_args;
1418 mono_threadpool_ms_remove_domain_jobs (MonoDomain *domain, int timeout)
1420 gboolean res = TRUE;
1425 g_assert (timeout >= -1);
1427 g_assert (mono_domain_is_unloading (domain));
1430 end = mono_msec_ticks () + timeout;
1432 #ifndef DISABLE_SOCKETS
1433 mono_threadpool_ms_io_remove_domain_jobs (domain);
1434 if (timeout != -1) {
1435 if (mono_msec_ticks () > end)
1441 * There might be some threads out that could be about to execute stuff from the given domain.
1442 * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
1444 sem = domain->cleanup_semaphore = CreateSemaphore (NULL, 0, 1, NULL);
1447 * The memory barrier here is required to have global ordering between assigning to cleanup_semaphone
1448 * and reading threadpool_jobs. Otherwise this thread could read a stale version of threadpool_jobs
1451 mono_memory_write_barrier ();
1453 while (domain->threadpool_jobs) {
1456 if (timeout != -1) {
1457 now = mono_msec_ticks ();
1465 WaitForSingleObject (sem, timeout != -1 ? end - now : timeout);
1469 domain->cleanup_semaphore = NULL;
1476 mono_threadpool_ms_suspend (void)
1479 threadpool->suspended = TRUE;
1483 mono_threadpool_ms_resume (void)
1486 threadpool->suspended = FALSE;
1490 ves_icall_System_Threading_ThreadPool_GetAvailableThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
1492 ThreadPoolCounter counter;
1494 if (!worker_threads || !completion_port_threads)
1497 mono_lazy_initialize (&status, initialize);
1499 counter.as_gint64 = COUNTER_READ ();
1501 *worker_threads = MAX (0, threadpool->limit_worker_max - counter._.active);
1502 *completion_port_threads = threadpool->limit_io_max;
1506 ves_icall_System_Threading_ThreadPool_GetMinThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
1508 if (!worker_threads || !completion_port_threads)
1511 mono_lazy_initialize (&status, initialize);
1513 *worker_threads = threadpool->limit_worker_min;
1514 *completion_port_threads = threadpool->limit_io_min;
1518 ves_icall_System_Threading_ThreadPool_GetMaxThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
1520 if (!worker_threads || !completion_port_threads)
1523 mono_lazy_initialize (&status, initialize);
1525 *worker_threads = threadpool->limit_worker_max;
1526 *completion_port_threads = threadpool->limit_io_max;
1530 ves_icall_System_Threading_ThreadPool_SetMinThreadsNative (gint32 worker_threads, gint32 completion_port_threads)
1532 mono_lazy_initialize (&status, initialize);
1534 if (worker_threads <= 0 || worker_threads > threadpool->limit_worker_max)
1536 if (completion_port_threads <= 0 || completion_port_threads > threadpool->limit_io_max)
1539 threadpool->limit_worker_min = worker_threads;
1540 threadpool->limit_io_min = completion_port_threads;
1546 ves_icall_System_Threading_ThreadPool_SetMaxThreadsNative (gint32 worker_threads, gint32 completion_port_threads)
1548 gint cpu_count = mono_cpu_count ();
1550 mono_lazy_initialize (&status, initialize);
1552 if (worker_threads < threadpool->limit_worker_min || worker_threads < cpu_count)
1554 if (completion_port_threads < threadpool->limit_io_min || completion_port_threads < cpu_count)
1557 threadpool->limit_worker_max = worker_threads;
1558 threadpool->limit_io_max = completion_port_threads;
1564 ves_icall_System_Threading_ThreadPool_InitializeVMTp (MonoBoolean *enable_worker_tracking)
1566 if (enable_worker_tracking) {
1567 // TODO implement some kind of switch to have the possibily to use it
1568 *enable_worker_tracking = FALSE;
1571 mono_lazy_initialize (&status, initialize);
1575 ves_icall_System_Threading_ThreadPool_NotifyWorkItemComplete (void)
1577 ThreadPoolCounter counter;
1579 if (mono_domain_is_unloading (mono_domain_get ()) || mono_runtime_is_shutting_down ())
1582 heuristic_notify_work_completed ();
1584 if (heuristic_should_adjust ())
1585 heuristic_adjust ();
1587 counter.as_gint64 = COUNTER_READ ();
1588 return counter._.working <= counter._.max_working;
1592 ves_icall_System_Threading_ThreadPool_NotifyWorkItemProgressNative (void)
1594 heuristic_notify_work_completed ();
1596 if (heuristic_should_adjust ())
1597 heuristic_adjust ();
1601 ves_icall_System_Threading_ThreadPool_ReportThreadStatus (MonoBoolean is_working)
1605 mono_error_set_not_implemented (&error, "");
1606 mono_error_set_pending_exception (&error);
1610 ves_icall_System_Threading_ThreadPool_RequestWorkerThread (void)
1612 return worker_request (mono_domain_get ());
1615 MonoBoolean G_GNUC_UNUSED
1616 ves_icall_System_Threading_ThreadPool_PostQueuedCompletionStatus (MonoNativeOverlapped *native_overlapped)
1618 /* This copy the behavior of the current Mono implementation */
1620 mono_error_set_not_implemented (&error, "");
1621 mono_error_set_pending_exception (&error);
1625 MonoBoolean G_GNUC_UNUSED
1626 ves_icall_System_Threading_ThreadPool_BindIOCompletionCallbackNative (gpointer file_handle)
1628 /* This copy the behavior of the current Mono implementation */
1632 MonoBoolean G_GNUC_UNUSED
1633 ves_icall_System_Threading_ThreadPool_IsThreadPoolHosted (void)