2 * threadpool-ms.c: Microsoft threadpool runtime support
5 * Ludovic Henry (ludovic.henry@xamarin.com)
7 * Copyright 2015 Xamarin, Inc (http://www.xamarin.com)
11 // Copyright (c) Microsoft. All rights reserved.
12 // Licensed under the MIT license. See LICENSE file in the project root for full license information.
15 // - src/vm/comthreadpool.cpp
16 // - src/vm/win32threadpoolcpp
17 // - src/vm/threadpoolrequest.cpp
18 // - src/vm/hillclimbing.cpp
20 // Ported from C++ to C and adjusted to Mono runtime
23 #define _USE_MATH_DEFINES // needed by MSVC to define math constants
28 #include <mono/metadata/class-internals.h>
29 #include <mono/metadata/exception.h>
30 #include <mono/metadata/gc-internals.h>
31 #include <mono/metadata/object.h>
32 #include <mono/metadata/object-internals.h>
33 #include <mono/metadata/threadpool-ms.h>
34 #include <mono/metadata/threadpool-ms-io.h>
35 #include <mono/utils/atomic.h>
36 #include <mono/utils/mono-compiler.h>
37 #include <mono/utils/mono-complex.h>
38 #include <mono/utils/mono-lazy-init.h>
39 #include <mono/utils/mono-logger.h>
40 #include <mono/utils/mono-logger-internals.h>
41 #include <mono/utils/mono-proclib.h>
42 #include <mono/utils/mono-threads.h>
43 #include <mono/utils/mono-time.h>
44 #include <mono/utils/mono-rand.h>
46 #define CPU_USAGE_LOW 80
47 #define CPU_USAGE_HIGH 95
49 #define MONITOR_INTERVAL 100 // ms
50 #define MONITOR_MINIMAL_LIFETIME 60 * 1000 // ms
52 #define WORKER_CREATION_MAX_PER_SEC 10
54 /* The exponent to apply to the gain. 1.0 means to use linear gain,
55 * higher values will enhance large moves and damp small ones.
57 #define HILL_CLIMBING_GAIN_EXPONENT 2.0
59 /* The 'cost' of a thread. 0 means drive for increased throughput regardless
60 * of thread count, higher values bias more against higher thread counts.
62 #define HILL_CLIMBING_BIAS 0.15
64 #define HILL_CLIMBING_WAVE_PERIOD 4
65 #define HILL_CLIMBING_MAX_WAVE_MAGNITUDE 20
66 #define HILL_CLIMBING_WAVE_MAGNITUDE_MULTIPLIER 1.0
67 #define HILL_CLIMBING_WAVE_HISTORY_SIZE 8
68 #define HILL_CLIMBING_TARGET_SIGNAL_TO_NOISE_RATIO 3.0
69 #define HILL_CLIMBING_MAX_CHANGE_PER_SECOND 4
70 #define HILL_CLIMBING_MAX_CHANGE_PER_SAMPLE 20
71 #define HILL_CLIMBING_SAMPLE_INTERVAL_LOW 10
72 #define HILL_CLIMBING_SAMPLE_INTERVAL_HIGH 200
73 #define HILL_CLIMBING_ERROR_SMOOTHING_FACTOR 0.01
74 #define HILL_CLIMBING_MAX_SAMPLE_ERROR_PERCENT 0.15
78 gint16 max_working; /* determined by heuristic */
79 gint16 active; /* executing worker_thread */
80 gint16 working; /* actively executing worker_thread, not parked */
81 gint16 parked; /* parked */
88 gint32 outstanding_request;
91 typedef MonoInternalThread ThreadPoolWorkingThread;
95 gint32 samples_to_measure;
96 gdouble target_throughput_ratio;
97 gdouble target_signal_to_noise_ratio;
98 gdouble max_change_per_second;
99 gdouble max_change_per_sample;
100 gint32 max_thread_wave_magnitude;
101 gint32 sample_interval_low;
102 gdouble thread_magnitude_multiplier;
103 gint32 sample_interval_high;
104 gdouble throughput_error_smoothing_factor;
105 gdouble gain_exponent;
106 gdouble max_sample_error;
108 gdouble current_control_setting;
109 gint64 total_samples;
110 gint16 last_thread_count;
111 gdouble elapsed_since_last_change;
112 gdouble completions_since_last_change;
114 gdouble average_throughput_noise;
117 gdouble *thread_counts;
119 guint32 current_sample_interval;
120 gpointer random_interval_generator;
122 gint32 accumulated_completion_count;
123 gdouble accumulated_sample_duration;
124 } ThreadPoolHillClimbing;
127 ThreadPoolCounter counters;
129 GPtrArray *domains; // ThreadPoolDomain* []
130 MonoCoopMutex domains_lock;
132 GPtrArray *working_threads; // ThreadPoolWorkingThread* []
133 gint32 parked_threads_count;
134 MonoCoopCond parked_threads_cond;
135 MonoCoopMutex active_threads_lock; /* protect access to working_threads and parked_threads */
137 guint32 worker_creation_current_second;
138 guint32 worker_creation_current_count;
139 MonoCoopMutex worker_creation_lock;
141 gint32 heuristic_completions;
142 guint32 heuristic_sample_start;
143 guint32 heuristic_last_dequeue; // ms
144 guint32 heuristic_last_adjustment; // ms
145 guint32 heuristic_adjustment_interval; // ms
146 ThreadPoolHillClimbing heuristic_hill_climbing;
147 MonoCoopMutex heuristic_lock;
149 gint32 limit_worker_min;
150 gint32 limit_worker_max;
154 MonoCpuUsageState *cpu_usage_state;
157 /* suspended by the debugger */
163 TRANSITION_INITIALIZING,
164 TRANSITION_RANDOM_MOVE,
165 TRANSITION_CLIMBING_MOVE,
166 TRANSITION_CHANGE_POINT,
167 TRANSITION_STABILIZING,
168 TRANSITION_STARVATION,
169 TRANSITION_THREAD_TIMED_OUT,
170 TRANSITION_UNDEFINED,
171 } ThreadPoolHeuristicStateTransition;
173 static mono_lazy_init_t status = MONO_LAZY_INIT_STATUS_NOT_INITIALIZED;
176 MONITOR_STATUS_REQUESTED,
177 MONITOR_STATUS_WAITING_FOR_REQUEST,
178 MONITOR_STATUS_NOT_RUNNING,
181 static gint32 monitor_status = MONITOR_STATUS_NOT_RUNNING;
183 static ThreadPool* threadpool;
185 #define COUNTER_CHECK(counter) \
187 g_assert (counter._.max_working > 0); \
188 g_assert (counter._.working >= 0); \
189 g_assert (counter._.active >= 0); \
192 #define COUNTER_READ() (InterlockedRead64 (&threadpool->counters.as_gint64))
194 #define COUNTER_ATOMIC(var,block) \
196 ThreadPoolCounter __old; \
198 g_assert (threadpool); \
199 __old.as_gint64 = COUNTER_READ (); \
202 COUNTER_CHECK (var); \
203 } while (InterlockedCompareExchange64 (&threadpool->counters.as_gint64, (var).as_gint64, __old.as_gint64) != __old.as_gint64); \
206 #define COUNTER_TRY_ATOMIC(res,var,block) \
208 ThreadPoolCounter __old; \
210 g_assert (threadpool); \
211 __old.as_gint64 = COUNTER_READ (); \
215 COUNTER_CHECK (var); \
216 (res) = InterlockedCompareExchange64 (&threadpool->counters.as_gint64, (var).as_gint64, __old.as_gint64) == __old.as_gint64; \
224 return mono_rand_init (NULL, 0);
228 rand_next (gpointer *handle, guint32 min, guint32 max)
231 if (!mono_rand_try_get_uint32 (handle, &val, min, max)) {
232 // FIXME handle error
233 g_assert_not_reached ();
239 rand_free (gpointer handle)
241 mono_rand_close (handle);
247 ThreadPoolHillClimbing *hc;
248 const char *threads_per_cpu_env;
249 gint threads_per_cpu;
252 g_assert (!threadpool);
253 threadpool = g_new0 (ThreadPool, 1);
254 g_assert (threadpool);
256 threadpool->domains = g_ptr_array_new ();
257 mono_coop_mutex_init (&threadpool->domains_lock);
259 threadpool->parked_threads_count = 0;
260 mono_coop_cond_init (&threadpool->parked_threads_cond);
261 threadpool->working_threads = g_ptr_array_new ();
262 mono_coop_mutex_init (&threadpool->active_threads_lock);
264 threadpool->worker_creation_current_second = -1;
265 mono_coop_mutex_init (&threadpool->worker_creation_lock);
267 threadpool->heuristic_adjustment_interval = 10;
268 mono_coop_mutex_init (&threadpool->heuristic_lock);
272 hc = &threadpool->heuristic_hill_climbing;
274 hc->wave_period = HILL_CLIMBING_WAVE_PERIOD;
275 hc->max_thread_wave_magnitude = HILL_CLIMBING_MAX_WAVE_MAGNITUDE;
276 hc->thread_magnitude_multiplier = (gdouble) HILL_CLIMBING_WAVE_MAGNITUDE_MULTIPLIER;
277 hc->samples_to_measure = hc->wave_period * HILL_CLIMBING_WAVE_HISTORY_SIZE;
278 hc->target_throughput_ratio = (gdouble) HILL_CLIMBING_BIAS;
279 hc->target_signal_to_noise_ratio = (gdouble) HILL_CLIMBING_TARGET_SIGNAL_TO_NOISE_RATIO;
280 hc->max_change_per_second = (gdouble) HILL_CLIMBING_MAX_CHANGE_PER_SECOND;
281 hc->max_change_per_sample = (gdouble) HILL_CLIMBING_MAX_CHANGE_PER_SAMPLE;
282 hc->sample_interval_low = HILL_CLIMBING_SAMPLE_INTERVAL_LOW;
283 hc->sample_interval_high = HILL_CLIMBING_SAMPLE_INTERVAL_HIGH;
284 hc->throughput_error_smoothing_factor = (gdouble) HILL_CLIMBING_ERROR_SMOOTHING_FACTOR;
285 hc->gain_exponent = (gdouble) HILL_CLIMBING_GAIN_EXPONENT;
286 hc->max_sample_error = (gdouble) HILL_CLIMBING_MAX_SAMPLE_ERROR_PERCENT;
287 hc->current_control_setting = 0;
288 hc->total_samples = 0;
289 hc->last_thread_count = 0;
290 hc->average_throughput_noise = 0;
291 hc->elapsed_since_last_change = 0;
292 hc->accumulated_completion_count = 0;
293 hc->accumulated_sample_duration = 0;
294 hc->samples = g_new0 (gdouble, hc->samples_to_measure);
295 hc->thread_counts = g_new0 (gdouble, hc->samples_to_measure);
296 hc->random_interval_generator = rand_create ();
297 hc->current_sample_interval = rand_next (&hc->random_interval_generator, hc->sample_interval_low, hc->sample_interval_high);
299 if (!(threads_per_cpu_env = g_getenv ("MONO_THREADS_PER_CPU")))
302 threads_per_cpu = CLAMP (atoi (threads_per_cpu_env), 1, 50);
304 threads_count = mono_cpu_count () * threads_per_cpu;
306 threadpool->limit_worker_min = threadpool->limit_io_min = threads_count;
308 #if defined (PLATFORM_ANDROID) || defined (HOST_IOS)
309 threadpool->limit_worker_max = threadpool->limit_io_max = CLAMP (threads_count * 100, MIN (threads_count, 200), MAX (threads_count, 200));
311 threadpool->limit_worker_max = threadpool->limit_io_max = threads_count * 100;
314 threadpool->counters._.max_working = threadpool->limit_worker_min;
316 threadpool->cpu_usage_state = g_new0 (MonoCpuUsageState, 1);
318 threadpool->suspended = FALSE;
321 static void worker_kill (ThreadPoolWorkingThread *thread);
328 /* we make the assumption along the code that we are
329 * cleaning up only if the runtime is shutting down */
330 g_assert (mono_runtime_is_shutting_down ());
332 while (monitor_status != MONITOR_STATUS_NOT_RUNNING)
333 mono_thread_info_sleep (1, NULL);
335 mono_coop_mutex_lock (&threadpool->active_threads_lock);
337 /* stop all threadpool->working_threads */
338 for (i = 0; i < threadpool->working_threads->len; ++i)
339 worker_kill ((ThreadPoolWorkingThread*) g_ptr_array_index (threadpool->working_threads, i));
341 /* unpark all threadpool->parked_threads */
342 mono_coop_cond_broadcast (&threadpool->parked_threads_cond);
344 mono_coop_mutex_unlock (&threadpool->active_threads_lock);
348 mono_threadpool_ms_enqueue_work_item (MonoDomain *domain, MonoObject *work_item)
350 static MonoClass *threadpool_class = NULL;
351 static MonoMethod *unsafe_queue_custom_work_item_method = NULL;
352 MonoDomain *current_domain;
356 g_assert (work_item);
358 if (!threadpool_class)
359 threadpool_class = mono_class_from_name (mono_defaults.corlib, "System.Threading", "ThreadPool");
360 g_assert (threadpool_class);
362 if (!unsafe_queue_custom_work_item_method)
363 unsafe_queue_custom_work_item_method = mono_class_get_method_from_name (threadpool_class, "UnsafeQueueCustomWorkItem", 2);
364 g_assert (unsafe_queue_custom_work_item_method);
368 args [0] = (gpointer) work_item;
369 args [1] = (gpointer) &f;
371 current_domain = mono_domain_get ();
372 if (current_domain == domain) {
373 mono_runtime_invoke (unsafe_queue_custom_work_item_method, NULL, args, NULL);
375 mono_thread_push_appdomain_ref (domain);
376 if (mono_domain_set (domain, FALSE)) {
377 mono_runtime_invoke (unsafe_queue_custom_work_item_method, NULL, args, NULL);
378 mono_domain_set (current_domain, TRUE);
380 mono_thread_pop_appdomain_ref ();
384 /* LOCKING: threadpool->domains_lock must be held */
386 domain_add (ThreadPoolDomain *tpdomain)
392 len = threadpool->domains->len;
393 for (i = 0; i < len; ++i) {
394 if (g_ptr_array_index (threadpool->domains, i) == tpdomain)
399 g_ptr_array_add (threadpool->domains, tpdomain);
402 /* LOCKING: threadpool->domains_lock must be held */
404 domain_remove (ThreadPoolDomain *tpdomain)
407 return g_ptr_array_remove (threadpool->domains, tpdomain);
410 /* LOCKING: threadpool->domains_lock must be held */
411 static ThreadPoolDomain *
412 domain_get (MonoDomain *domain, gboolean create)
414 ThreadPoolDomain *tpdomain = NULL;
419 for (i = 0; i < threadpool->domains->len; ++i) {
420 tpdomain = (ThreadPoolDomain *)g_ptr_array_index (threadpool->domains, i);
421 if (tpdomain->domain == domain)
426 tpdomain = g_new0 (ThreadPoolDomain, 1);
427 tpdomain->domain = domain;
428 domain_add (tpdomain);
435 domain_free (ThreadPoolDomain *tpdomain)
440 /* LOCKING: threadpool->domains_lock must be held */
442 domain_any_has_request (void)
446 for (i = 0; i < threadpool->domains->len; ++i) {
447 ThreadPoolDomain *tmp = (ThreadPoolDomain *)g_ptr_array_index (threadpool->domains, i);
448 if (tmp->outstanding_request > 0)
455 /* LOCKING: threadpool->domains_lock must be held */
456 static ThreadPoolDomain *
457 domain_get_next (ThreadPoolDomain *current)
459 ThreadPoolDomain *tpdomain = NULL;
462 len = threadpool->domains->len;
464 guint i, current_idx = -1;
466 for (i = 0; i < len; ++i) {
467 if (current == g_ptr_array_index (threadpool->domains, i)) {
472 g_assert (current_idx >= 0);
474 for (i = current_idx + 1; i < len + current_idx + 1; ++i) {
475 ThreadPoolDomain *tmp = (ThreadPoolDomain *)g_ptr_array_index (threadpool->domains, i % len);
476 if (tmp->outstanding_request > 0) {
487 worker_wait_interrupt (gpointer data)
489 mono_coop_mutex_lock (&threadpool->active_threads_lock);
490 mono_coop_cond_signal (&threadpool->parked_threads_cond);
491 mono_coop_mutex_unlock (&threadpool->active_threads_lock);
494 /* return TRUE if timeout, FALSE otherwise (worker unpark or interrupt) */
498 gboolean timeout = FALSE;
500 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] current worker parking", mono_native_thread_id_get ());
502 mono_gc_set_skip_thread (TRUE);
504 mono_coop_mutex_lock (&threadpool->active_threads_lock);
506 if (!mono_runtime_is_shutting_down ()) {
507 static gpointer rand_handle = NULL;
508 MonoInternalThread *thread_internal;
509 gboolean interrupted = FALSE;
512 rand_handle = rand_create ();
513 g_assert (rand_handle);
515 thread_internal = mono_thread_internal_current ();
516 g_assert (thread_internal);
518 threadpool->parked_threads_count += 1;
519 g_ptr_array_remove_fast (threadpool->working_threads, thread_internal);
521 mono_thread_info_install_interrupt (worker_wait_interrupt, NULL, &interrupted);
525 if (mono_coop_cond_timedwait (&threadpool->parked_threads_cond, &threadpool->active_threads_lock, rand_next ((void **)rand_handle, 5 * 1000, 60 * 1000)) != 0)
528 mono_thread_info_uninstall_interrupt (&interrupted);
531 g_ptr_array_add (threadpool->working_threads, thread_internal);
532 threadpool->parked_threads_count -= 1;
535 mono_coop_mutex_unlock (&threadpool->active_threads_lock);
537 mono_gc_set_skip_thread (FALSE);
539 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] current worker unparking, timeout? %s", mono_native_thread_id_get (), timeout ? "yes" : "no");
545 worker_try_unpark (void)
547 gboolean res = FALSE;
549 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try unpark worker", mono_native_thread_id_get ());
551 mono_coop_mutex_lock (&threadpool->active_threads_lock);
552 if (threadpool->parked_threads_count > 0) {
553 mono_coop_cond_signal (&threadpool->parked_threads_cond);
556 mono_coop_mutex_unlock (&threadpool->active_threads_lock);
558 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try unpark worker, success? %s", mono_native_thread_id_get (), res ? "yes" : "no");
564 worker_kill (ThreadPoolWorkingThread *thread)
566 if (thread == mono_thread_internal_current ())
569 mono_thread_internal_stop ((MonoInternalThread*) thread);
573 worker_thread (gpointer data)
575 MonoInternalThread *thread;
576 ThreadPoolDomain *tpdomain, *previous_tpdomain;
577 ThreadPoolCounter counter;
578 gboolean retire = FALSE;
580 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_THREADPOOL, "[%p] worker starting", mono_native_thread_id_get ());
582 g_assert (threadpool);
584 thread = mono_thread_internal_current ();
587 mono_thread_set_name_internal (thread, mono_string_new (mono_domain_get (), "Threadpool worker"), FALSE);
589 mono_coop_mutex_lock (&threadpool->active_threads_lock);
590 g_ptr_array_add (threadpool->working_threads, thread);
591 mono_coop_mutex_unlock (&threadpool->active_threads_lock);
593 previous_tpdomain = NULL;
595 mono_coop_mutex_lock (&threadpool->domains_lock);
597 while (!mono_runtime_is_shutting_down ()) {
600 if ((thread->state & (ThreadState_StopRequested | ThreadState_SuspendRequested)) != 0) {
601 mono_coop_mutex_unlock (&threadpool->domains_lock);
602 mono_thread_interruption_checkpoint ();
603 mono_coop_mutex_lock (&threadpool->domains_lock);
606 if (retire || !(tpdomain = domain_get_next (previous_tpdomain))) {
609 COUNTER_ATOMIC (counter, {
610 counter._.working --;
614 mono_coop_mutex_unlock (&threadpool->domains_lock);
615 timeout = worker_park ();
616 mono_coop_mutex_lock (&threadpool->domains_lock);
618 COUNTER_ATOMIC (counter, {
619 counter._.working ++;
632 tpdomain->outstanding_request --;
633 g_assert (tpdomain->outstanding_request >= 0);
635 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] worker running in domain %p",
636 mono_native_thread_id_get (), tpdomain->domain, tpdomain->outstanding_request);
638 g_assert (tpdomain->domain);
639 g_assert (tpdomain->domain->threadpool_jobs >= 0);
640 tpdomain->domain->threadpool_jobs ++;
642 mono_coop_mutex_unlock (&threadpool->domains_lock);
644 mono_thread_push_appdomain_ref (tpdomain->domain);
645 if (mono_domain_set (tpdomain->domain, FALSE)) {
646 MonoObject *exc = NULL;
647 MonoObject *res = mono_runtime_invoke (mono_defaults.threadpool_perform_wait_callback_method, NULL, NULL, &exc);
649 mono_thread_internal_unhandled_exception (exc);
650 else if (res && *(MonoBoolean*) mono_object_unbox (res) == FALSE)
653 mono_thread_clr_state (thread, (MonoThreadState)~ThreadState_Background);
654 if (!mono_thread_test_state (thread , ThreadState_Background))
655 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
657 mono_domain_set (mono_get_root_domain (), TRUE);
659 mono_thread_pop_appdomain_ref ();
661 mono_coop_mutex_lock (&threadpool->domains_lock);
663 tpdomain->domain->threadpool_jobs --;
664 g_assert (tpdomain->domain->threadpool_jobs >= 0);
666 if (tpdomain->domain->threadpool_jobs == 0 && mono_domain_is_unloading (tpdomain->domain)) {
667 gboolean removed = domain_remove (tpdomain);
669 if (tpdomain->domain->cleanup_semaphore)
670 ReleaseSemaphore (tpdomain->domain->cleanup_semaphore, 1, NULL);
671 domain_free (tpdomain);
675 previous_tpdomain = tpdomain;
678 mono_coop_mutex_unlock (&threadpool->domains_lock);
680 mono_coop_mutex_lock (&threadpool->active_threads_lock);
681 g_ptr_array_remove_fast (threadpool->working_threads, thread);
682 mono_coop_mutex_unlock (&threadpool->active_threads_lock);
684 COUNTER_ATOMIC (counter, {
689 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_THREADPOOL, "[%p] worker finishing", mono_native_thread_id_get ());
693 worker_try_create (void)
695 ThreadPoolCounter counter;
696 MonoInternalThread *thread;
699 mono_coop_mutex_lock (&threadpool->worker_creation_lock);
701 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker", mono_native_thread_id_get ());
703 if ((now = mono_100ns_ticks () / 10 / 1000 / 1000) == 0) {
704 g_warning ("failed to get 100ns ticks");
706 if (threadpool->worker_creation_current_second != now) {
707 threadpool->worker_creation_current_second = now;
708 threadpool->worker_creation_current_count = 0;
710 g_assert (threadpool->worker_creation_current_count <= WORKER_CREATION_MAX_PER_SEC);
711 if (threadpool->worker_creation_current_count == WORKER_CREATION_MAX_PER_SEC) {
712 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",
713 mono_native_thread_id_get (), threadpool->worker_creation_current_count);
714 mono_coop_mutex_unlock (&threadpool->worker_creation_lock);
720 COUNTER_ATOMIC (counter, {
721 if (counter._.working >= counter._.max_working) {
722 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker, failed: maximum number of working threads reached",
723 mono_native_thread_id_get ());
724 mono_coop_mutex_unlock (&threadpool->worker_creation_lock);
727 counter._.working ++;
731 if ((thread = mono_thread_create_internal (mono_get_root_domain (), worker_thread, NULL, TRUE, 0)) != NULL) {
732 threadpool->worker_creation_current_count += 1;
734 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);
735 mono_coop_mutex_unlock (&threadpool->worker_creation_lock);
739 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker, failed: could not create thread", mono_native_thread_id_get ());
741 COUNTER_ATOMIC (counter, {
742 counter._.working --;
746 mono_coop_mutex_unlock (&threadpool->worker_creation_lock);
750 static void monitor_ensure_running (void);
753 worker_request (MonoDomain *domain)
755 ThreadPoolDomain *tpdomain;
758 g_assert (threadpool);
760 if (mono_runtime_is_shutting_down ())
763 mono_coop_mutex_lock (&threadpool->domains_lock);
765 /* synchronize check with worker_thread */
766 if (mono_domain_is_unloading (domain)) {
767 mono_coop_mutex_unlock (&threadpool->domains_lock);
771 tpdomain = domain_get (domain, TRUE);
773 tpdomain->outstanding_request ++;
775 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] request worker, domain = %p, outstanding_request = %d",
776 mono_native_thread_id_get (), tpdomain->domain, tpdomain->outstanding_request);
778 mono_coop_mutex_unlock (&threadpool->domains_lock);
780 if (threadpool->suspended)
783 monitor_ensure_running ();
785 if (worker_try_unpark ()) {
786 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] request worker, unparked", mono_native_thread_id_get ());
790 if (worker_try_create ()) {
791 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] request worker, created", mono_native_thread_id_get ());
795 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] request worker, failed", mono_native_thread_id_get ());
800 monitor_should_keep_running (void)
802 static gint64 last_should_keep_running = -1;
804 g_assert (monitor_status == MONITOR_STATUS_WAITING_FOR_REQUEST || monitor_status == MONITOR_STATUS_REQUESTED);
806 if (InterlockedExchange (&monitor_status, MONITOR_STATUS_WAITING_FOR_REQUEST) == MONITOR_STATUS_WAITING_FOR_REQUEST) {
807 gboolean should_keep_running = TRUE, force_should_keep_running = FALSE;
809 if (mono_runtime_is_shutting_down ()) {
810 should_keep_running = FALSE;
812 mono_coop_mutex_lock (&threadpool->domains_lock);
813 if (!domain_any_has_request ())
814 should_keep_running = FALSE;
815 mono_coop_mutex_unlock (&threadpool->domains_lock);
817 if (!should_keep_running) {
818 if (last_should_keep_running == -1 || mono_100ns_ticks () - last_should_keep_running < MONITOR_MINIMAL_LIFETIME * 1000 * 10) {
819 should_keep_running = force_should_keep_running = TRUE;
824 if (should_keep_running) {
825 if (last_should_keep_running == -1 || !force_should_keep_running)
826 last_should_keep_running = mono_100ns_ticks ();
828 last_should_keep_running = -1;
829 if (InterlockedCompareExchange (&monitor_status, MONITOR_STATUS_NOT_RUNNING, MONITOR_STATUS_WAITING_FOR_REQUEST) == MONITOR_STATUS_WAITING_FOR_REQUEST)
834 g_assert (monitor_status == MONITOR_STATUS_WAITING_FOR_REQUEST || monitor_status == MONITOR_STATUS_REQUESTED);
840 monitor_sufficient_delay_since_last_dequeue (void)
844 g_assert (threadpool);
846 if (threadpool->cpu_usage < CPU_USAGE_LOW) {
847 threshold = MONITOR_INTERVAL;
849 ThreadPoolCounter counter;
850 counter.as_gint64 = COUNTER_READ();
851 threshold = counter._.max_working * MONITOR_INTERVAL * 2;
854 return mono_msec_ticks () >= threadpool->heuristic_last_dequeue + threshold;
857 static void hill_climbing_force_change (gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition);
860 monitor_thread (void)
862 MonoInternalThread *current_thread = mono_thread_internal_current ();
865 mono_cpu_usage (threadpool->cpu_usage_state);
867 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, started", mono_native_thread_id_get ());
870 MonoInternalThread *thread;
871 gboolean all_waitsleepjoin = TRUE;
872 gint32 interval_left = MONITOR_INTERVAL;
873 gint32 awake = 0; /* number of spurious awakes we tolerate before doing a round of rebalancing */
875 g_assert (monitor_status != MONITOR_STATUS_NOT_RUNNING);
877 mono_gc_set_skip_thread (TRUE);
881 gboolean alerted = FALSE;
883 if (mono_runtime_is_shutting_down ())
886 ts = mono_msec_ticks ();
887 if (mono_thread_info_sleep (interval_left, &alerted) == 0)
889 interval_left -= mono_msec_ticks () - ts;
891 mono_gc_set_skip_thread (FALSE);
892 if ((current_thread->state & (ThreadState_StopRequested | ThreadState_SuspendRequested)) != 0)
893 mono_thread_interruption_checkpoint ();
894 mono_gc_set_skip_thread (TRUE);
895 } while (interval_left > 0 && ++awake < 10);
897 mono_gc_set_skip_thread (FALSE);
899 if (threadpool->suspended)
902 if (mono_runtime_is_shutting_down ())
905 mono_coop_mutex_lock (&threadpool->domains_lock);
906 if (!domain_any_has_request ()) {
907 mono_coop_mutex_unlock (&threadpool->domains_lock);
910 mono_coop_mutex_unlock (&threadpool->domains_lock);
913 mono_coop_mutex_lock (&threadpool->active_threads_lock);
914 for (i = 0; i < threadpool->working_threads->len; ++i) {
915 thread = (MonoInternalThread *)g_ptr_array_index (threadpool->working_threads, i);
916 if ((thread->state & ThreadState_WaitSleepJoin) == 0) {
917 all_waitsleepjoin = FALSE;
921 mono_coop_mutex_unlock (&threadpool->active_threads_lock);
923 if (all_waitsleepjoin) {
924 ThreadPoolCounter counter;
925 gboolean limit_worker_max_reached = FALSE;
927 COUNTER_ATOMIC (counter, {
928 if (counter._.max_working >= threadpool->limit_worker_max) {
929 limit_worker_max_reached = TRUE;
932 counter._.max_working ++;
935 if (!limit_worker_max_reached)
936 hill_climbing_force_change (counter._.max_working, TRANSITION_STARVATION);
939 threadpool->cpu_usage = mono_cpu_usage (threadpool->cpu_usage_state);
941 if (monitor_sufficient_delay_since_last_dequeue ()) {
942 for (i = 0; i < 5; ++i) {
943 if (mono_runtime_is_shutting_down ())
946 if (worker_try_unpark ()) {
947 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, unparked", mono_native_thread_id_get ());
951 if (worker_try_create ()) {
952 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, created", mono_native_thread_id_get ());
957 } while (monitor_should_keep_running ());
959 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, finished", mono_native_thread_id_get ());
963 monitor_ensure_running (void)
966 switch (monitor_status) {
967 case MONITOR_STATUS_REQUESTED:
969 case MONITOR_STATUS_WAITING_FOR_REQUEST:
970 InterlockedCompareExchange (&monitor_status, MONITOR_STATUS_REQUESTED, MONITOR_STATUS_WAITING_FOR_REQUEST);
972 case MONITOR_STATUS_NOT_RUNNING:
973 if (mono_runtime_is_shutting_down ())
975 if (InterlockedCompareExchange (&monitor_status, MONITOR_STATUS_REQUESTED, MONITOR_STATUS_NOT_RUNNING) == MONITOR_STATUS_NOT_RUNNING) {
976 if (!mono_thread_create_internal (mono_get_root_domain (), monitor_thread, NULL, TRUE, SMALL_STACK))
977 monitor_status = MONITOR_STATUS_NOT_RUNNING;
981 default: g_assert_not_reached ();
987 hill_climbing_change_thread_count (gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition)
989 ThreadPoolHillClimbing *hc;
991 g_assert (threadpool);
993 hc = &threadpool->heuristic_hill_climbing;
995 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);
997 hc->last_thread_count = new_thread_count;
998 hc->current_sample_interval = rand_next (&hc->random_interval_generator, hc->sample_interval_low, hc->sample_interval_high);
999 hc->elapsed_since_last_change = 0;
1000 hc->completions_since_last_change = 0;
1004 hill_climbing_force_change (gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition)
1006 ThreadPoolHillClimbing *hc;
1008 g_assert (threadpool);
1010 hc = &threadpool->heuristic_hill_climbing;
1012 if (new_thread_count != hc->last_thread_count) {
1013 hc->current_control_setting += new_thread_count - hc->last_thread_count;
1014 hill_climbing_change_thread_count (new_thread_count, transition);
1018 static double_complex
1019 hill_climbing_get_wave_component (gdouble *samples, guint sample_count, gdouble period)
1021 ThreadPoolHillClimbing *hc;
1022 gdouble w, cosine, sine, coeff, q0, q1, q2;
1025 g_assert (threadpool);
1026 g_assert (sample_count >= period);
1027 g_assert (period >= 2);
1029 hc = &threadpool->heuristic_hill_climbing;
1031 w = 2.0 * M_PI / period;
1034 coeff = 2.0 * cosine;
1037 for (i = 0; i < sample_count; ++i) {
1038 q0 = coeff * q1 - q2 + samples [(hc->total_samples - sample_count + i) % hc->samples_to_measure];
1043 return mono_double_complex_scalar_div (mono_double_complex_make (q1 - q2 * cosine, (q2 * sine)), ((gdouble)sample_count));
1047 hill_climbing_update (gint16 current_thread_count, guint32 sample_duration, gint32 completions, guint32 *adjustment_interval)
1049 ThreadPoolHillClimbing *hc;
1050 ThreadPoolHeuristicStateTransition transition;
1052 gdouble throughput_error_estimate;
1058 gint new_thread_wave_magnitude;
1059 gint new_thread_count;
1060 double_complex thread_wave_component;
1061 double_complex throughput_wave_component;
1062 double_complex ratio;
1064 g_assert (threadpool);
1065 g_assert (adjustment_interval);
1067 hc = &threadpool->heuristic_hill_climbing;
1069 /* If someone changed the thread count without telling us, update our records accordingly. */
1070 if (current_thread_count != hc->last_thread_count)
1071 hill_climbing_force_change (current_thread_count, TRANSITION_INITIALIZING);
1073 /* Update the cumulative stats for this thread count */
1074 hc->elapsed_since_last_change += sample_duration;
1075 hc->completions_since_last_change += completions;
1077 /* Add in any data we've already collected about this sample */
1078 sample_duration += hc->accumulated_sample_duration;
1079 completions += hc->accumulated_completion_count;
1081 /* We need to make sure we're collecting reasonably accurate data. Since we're just counting the end
1082 * of each work item, we are goinng to be missing some data about what really happened during the
1083 * sample interval. The count produced by each thread includes an initial work item that may have
1084 * started well before the start of the interval, and each thread may have been running some new
1085 * work item for some time before the end of the interval, which did not yet get counted. So
1086 * our count is going to be off by +/- threadCount workitems.
1088 * The exception is that the thread that reported to us last time definitely wasn't running any work
1089 * at that time, and the thread that's reporting now definitely isn't running a work item now. So
1090 * we really only need to consider threadCount-1 threads.
1092 * Thus the percent error in our count is +/- (threadCount-1)/numCompletions.
1094 * We cannot rely on the frequency-domain analysis we'll be doing later to filter out this error, because
1095 * of the way it accumulates over time. If this sample is off by, say, 33% in the negative direction,
1096 * then the next one likely will be too. The one after that will include the sum of the completions
1097 * we missed in the previous samples, and so will be 33% positive. So every three samples we'll have
1098 * two "low" samples and one "high" sample. This will appear as periodic variation right in the frequency
1099 * range we're targeting, which will not be filtered by the frequency-domain translation. */
1100 if (hc->total_samples > 0 && ((current_thread_count - 1.0) / completions) >= hc->max_sample_error) {
1101 /* Not accurate enough yet. Let's accumulate the data so
1102 * far, and tell the ThreadPool to collect a little more. */
1103 hc->accumulated_sample_duration = sample_duration;
1104 hc->accumulated_completion_count = completions;
1105 *adjustment_interval = 10;
1106 return current_thread_count;
1109 /* We've got enouugh data for our sample; reset our accumulators for next time. */
1110 hc->accumulated_sample_duration = 0;
1111 hc->accumulated_completion_count = 0;
1113 /* Add the current thread count and throughput sample to our history. */
1114 throughput = ((gdouble) completions) / sample_duration;
1116 sample_index = hc->total_samples % hc->samples_to_measure;
1117 hc->samples [sample_index] = throughput;
1118 hc->thread_counts [sample_index] = current_thread_count;
1119 hc->total_samples ++;
1121 /* Set up defaults for our metrics. */
1122 thread_wave_component = mono_double_complex_make(0, 0);
1123 throughput_wave_component = mono_double_complex_make(0, 0);
1124 throughput_error_estimate = 0;
1125 ratio = mono_double_complex_make(0, 0);
1128 transition = TRANSITION_WARMUP;
1130 /* How many samples will we use? It must be at least the three wave periods we're looking for, and it must also
1131 * be a whole multiple of the primary wave's period; otherwise the frequency we're looking for will fall between
1132 * two frequency bands in the Fourier analysis, and we won't be able to measure it accurately. */
1133 sample_count = ((gint) MIN (hc->total_samples - 1, hc->samples_to_measure) / hc->wave_period) * hc->wave_period;
1135 if (sample_count > hc->wave_period) {
1137 gdouble average_throughput;
1138 gdouble average_thread_count;
1139 gdouble sample_sum = 0;
1140 gdouble thread_sum = 0;
1142 /* Average the throughput and thread count samples, so we can scale the wave magnitudes later. */
1143 for (i = 0; i < sample_count; ++i) {
1144 guint j = (hc->total_samples - sample_count + i) % hc->samples_to_measure;
1145 sample_sum += hc->samples [j];
1146 thread_sum += hc->thread_counts [j];
1149 average_throughput = sample_sum / sample_count;
1150 average_thread_count = thread_sum / sample_count;
1152 if (average_throughput > 0 && average_thread_count > 0) {
1153 gdouble noise_for_confidence, adjacent_period_1, adjacent_period_2;
1155 /* Calculate the periods of the adjacent frequency bands we'll be using to
1156 * measure noise levels. We want the two adjacent Fourier frequency bands. */
1157 adjacent_period_1 = sample_count / (((gdouble) sample_count) / ((gdouble) hc->wave_period) + 1);
1158 adjacent_period_2 = sample_count / (((gdouble) sample_count) / ((gdouble) hc->wave_period) - 1);
1160 /* Get the the three different frequency components of the throughput (scaled by average
1161 * throughput). Our "error" estimate (the amount of noise that might be present in the
1162 * frequency band we're really interested in) is the average of the adjacent bands. */
1163 throughput_wave_component = mono_double_complex_scalar_div (hill_climbing_get_wave_component (hc->samples, sample_count, hc->wave_period), average_throughput);
1164 throughput_error_estimate = cabs (mono_double_complex_scalar_div (hill_climbing_get_wave_component (hc->samples, sample_count, adjacent_period_1), average_throughput));
1166 if (adjacent_period_2 <= sample_count) {
1167 throughput_error_estimate = MAX (throughput_error_estimate, cabs (mono_double_complex_scalar_div (hill_climbing_get_wave_component (
1168 hc->samples, sample_count, adjacent_period_2), average_throughput)));
1171 /* Do the same for the thread counts, so we have something to compare to. We don't
1172 * measure thread count noise, because there is none; these are exact measurements. */
1173 thread_wave_component = mono_double_complex_scalar_div (hill_climbing_get_wave_component (hc->thread_counts, sample_count, hc->wave_period), average_thread_count);
1175 /* Update our moving average of the throughput noise. We'll use this
1176 * later as feedback to determine the new size of the thread wave. */
1177 if (hc->average_throughput_noise == 0) {
1178 hc->average_throughput_noise = throughput_error_estimate;
1180 hc->average_throughput_noise = (hc->throughput_error_smoothing_factor * throughput_error_estimate)
1181 + ((1.0 + hc->throughput_error_smoothing_factor) * hc->average_throughput_noise);
1184 if (cabs (thread_wave_component) > 0) {
1185 /* Adjust the throughput wave so it's centered around the target wave,
1186 * and then calculate the adjusted throughput/thread ratio. */
1187 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);
1188 transition = TRANSITION_CLIMBING_MOVE;
1190 ratio = mono_double_complex_make (0, 0);
1191 transition = TRANSITION_STABILIZING;
1194 noise_for_confidence = MAX (hc->average_throughput_noise, throughput_error_estimate);
1195 if (noise_for_confidence > 0) {
1196 confidence = cabs (thread_wave_component) / noise_for_confidence / hc->target_signal_to_noise_ratio;
1198 /* there is no noise! */
1204 /* We use just the real part of the complex ratio we just calculated. If the throughput signal
1205 * is exactly in phase with the thread signal, this will be the same as taking the magnitude of
1206 * the complex move and moving that far up. If they're 180 degrees out of phase, we'll move
1207 * backward (because this indicates that our changes are having the opposite of the intended effect).
1208 * If they're 90 degrees out of phase, we won't move at all, because we can't tell wether we're
1209 * having a negative or positive effect on throughput. */
1210 move = creal (ratio);
1211 move = CLAMP (move, -1.0, 1.0);
1213 /* Apply our confidence multiplier. */
1214 move *= CLAMP (confidence, -1.0, 1.0);
1216 /* Now apply non-linear gain, such that values around zero are attenuated, while higher values
1217 * are enhanced. This allows us to move quickly if we're far away from the target, but more slowly
1218 * if we're getting close, giving us rapid ramp-up without wild oscillations around the target. */
1219 gain = hc->max_change_per_second * sample_duration;
1220 move = pow (fabs (move), hc->gain_exponent) * (move >= 0.0 ? 1 : -1) * gain;
1221 move = MIN (move, hc->max_change_per_sample);
1223 /* If the result was positive, and CPU is > 95%, refuse the move. */
1224 if (move > 0.0 && threadpool->cpu_usage > CPU_USAGE_HIGH)
1227 /* Apply the move to our control setting. */
1228 hc->current_control_setting += move;
1230 /* Calculate the new thread wave magnitude, which is based on the moving average we've been keeping of the
1231 * throughput error. This average starts at zero, so we'll start with a nice safe little wave at first. */
1232 new_thread_wave_magnitude = (gint)(0.5 + (hc->current_control_setting * hc->average_throughput_noise
1233 * hc->target_signal_to_noise_ratio * hc->thread_magnitude_multiplier * 2.0));
1234 new_thread_wave_magnitude = CLAMP (new_thread_wave_magnitude, 1, hc->max_thread_wave_magnitude);
1236 /* Make sure our control setting is within the ThreadPool's limits. */
1237 hc->current_control_setting = CLAMP (hc->current_control_setting, threadpool->limit_worker_min, threadpool->limit_worker_max - new_thread_wave_magnitude);
1239 /* Calculate the new thread count (control setting + square wave). */
1240 new_thread_count = (gint)(hc->current_control_setting + new_thread_wave_magnitude * ((hc->total_samples / (hc->wave_period / 2)) % 2));
1242 /* Make sure the new thread count doesn't exceed the ThreadPool's limits. */
1243 new_thread_count = CLAMP (new_thread_count, threadpool->limit_worker_min, threadpool->limit_worker_max);
1245 if (new_thread_count != current_thread_count)
1246 hill_climbing_change_thread_count (new_thread_count, transition);
1248 if (creal (ratio) < 0.0 && new_thread_count == threadpool->limit_worker_min)
1249 *adjustment_interval = (gint)(0.5 + hc->current_sample_interval * (10.0 * MAX (-1.0 * creal (ratio), 1.0)));
1251 *adjustment_interval = hc->current_sample_interval;
1253 return new_thread_count;
1257 heuristic_notify_work_completed (void)
1259 g_assert (threadpool);
1261 InterlockedIncrement (&threadpool->heuristic_completions);
1262 threadpool->heuristic_last_dequeue = mono_msec_ticks ();
1266 heuristic_should_adjust (void)
1268 g_assert (threadpool);
1270 if (threadpool->heuristic_last_dequeue > threadpool->heuristic_last_adjustment + threadpool->heuristic_adjustment_interval) {
1271 ThreadPoolCounter counter;
1272 counter.as_gint64 = COUNTER_READ();
1273 if (counter._.working <= counter._.max_working)
1281 heuristic_adjust (void)
1283 g_assert (threadpool);
1285 if (mono_coop_mutex_trylock (&threadpool->heuristic_lock) == 0) {
1286 gint32 completions = InterlockedExchange (&threadpool->heuristic_completions, 0);
1287 guint32 sample_end = mono_msec_ticks ();
1288 guint32 sample_duration = sample_end - threadpool->heuristic_sample_start;
1290 if (sample_duration >= threadpool->heuristic_adjustment_interval / 2) {
1291 ThreadPoolCounter counter;
1292 gint16 new_thread_count;
1294 counter.as_gint64 = COUNTER_READ ();
1295 new_thread_count = hill_climbing_update (counter._.max_working, sample_duration, completions, &threadpool->heuristic_adjustment_interval);
1297 COUNTER_ATOMIC (counter, { counter._.max_working = new_thread_count; });
1299 if (new_thread_count > counter._.max_working)
1300 worker_request (mono_domain_get ());
1302 threadpool->heuristic_sample_start = sample_end;
1303 threadpool->heuristic_last_adjustment = mono_msec_ticks ();
1306 mono_coop_mutex_unlock (&threadpool->heuristic_lock);
1311 mono_threadpool_ms_cleanup (void)
1313 #ifndef DISABLE_SOCKETS
1314 mono_threadpool_ms_io_cleanup ();
1316 mono_lazy_cleanup (&status, cleanup);
1320 mono_threadpool_ms_begin_invoke (MonoDomain *domain, MonoObject *target, MonoMethod *method, gpointer *params)
1322 static MonoClass *async_call_klass = NULL;
1323 MonoMethodMessage *message;
1324 MonoAsyncResult *async_result;
1325 MonoAsyncCall *async_call;
1326 MonoDelegate *async_callback = NULL;
1327 MonoObject *state = NULL;
1329 if (!async_call_klass)
1330 async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
1331 g_assert (async_call_klass);
1333 mono_lazy_initialize (&status, initialize);
1335 message = mono_method_call_message_new (method, params, mono_get_delegate_invoke (method->klass), (params != NULL) ? (&async_callback) : NULL, (params != NULL) ? (&state) : NULL);
1337 async_call = (MonoAsyncCall*) mono_object_new (domain, async_call_klass);
1338 MONO_OBJECT_SETREF (async_call, msg, message);
1339 MONO_OBJECT_SETREF (async_call, state, state);
1341 if (async_callback) {
1342 MONO_OBJECT_SETREF (async_call, cb_method, mono_get_delegate_invoke (((MonoObject*) async_callback)->vtable->klass));
1343 MONO_OBJECT_SETREF (async_call, cb_target, async_callback);
1346 async_result = mono_async_result_new (domain, NULL, async_call->state, NULL, (MonoObject*) async_call);
1347 MONO_OBJECT_SETREF (async_result, async_delegate, target);
1349 mono_threadpool_ms_enqueue_work_item (domain, (MonoObject*) async_result);
1351 return async_result;
1355 mono_threadpool_ms_end_invoke (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1360 g_assert (out_args);
1365 /* check if already finished */
1366 mono_monitor_enter ((MonoObject*) ares);
1368 if (ares->endinvoke_called) {
1369 *exc = (MonoObject*) mono_get_exception_invalid_operation (NULL);
1370 mono_monitor_exit ((MonoObject*) ares);
1374 ares->endinvoke_called = 1;
1376 /* wait until we are really finished */
1377 if (ares->completed) {
1378 mono_monitor_exit ((MonoObject *) ares);
1380 gpointer wait_event;
1382 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle*) ares->handle);
1384 wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1385 g_assert(wait_event);
1386 MONO_OBJECT_SETREF (ares, handle, (MonoObject*) mono_wait_handle_new (mono_object_domain (ares), wait_event));
1388 mono_monitor_exit ((MonoObject*) ares);
1389 MONO_PREPARE_BLOCKING;
1390 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
1391 MONO_FINISH_BLOCKING;
1394 ac = (MonoAsyncCall*) ares->object_data;
1397 *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1398 *out_args = ac->out_args;
1403 mono_threadpool_ms_remove_domain_jobs (MonoDomain *domain, int timeout)
1405 gboolean res = TRUE;
1410 g_assert (timeout >= -1);
1412 g_assert (mono_domain_is_unloading (domain));
1415 start = mono_msec_ticks ();
1417 #ifndef DISABLE_SOCKETS
1418 mono_threadpool_ms_io_remove_domain_jobs (domain);
1419 if (timeout != -1) {
1420 timeout -= mono_msec_ticks () - start;
1427 * There might be some threads out that could be about to execute stuff from the given domain.
1428 * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
1430 sem = domain->cleanup_semaphore = CreateSemaphore (NULL, 0, 1, NULL);
1433 * The memory barrier here is required to have global ordering between assigning to cleanup_semaphone
1434 * and reading threadpool_jobs. Otherwise this thread could read a stale version of threadpool_jobs
1437 mono_memory_write_barrier ();
1439 while (domain->threadpool_jobs) {
1440 MONO_PREPARE_BLOCKING;
1441 WaitForSingleObject (sem, timeout);
1442 MONO_FINISH_BLOCKING;
1443 if (timeout != -1) {
1444 timeout -= mono_msec_ticks () - start;
1452 domain->cleanup_semaphore = NULL;
1459 mono_threadpool_ms_suspend (void)
1462 threadpool->suspended = TRUE;
1466 mono_threadpool_ms_resume (void)
1469 threadpool->suspended = FALSE;
1473 ves_icall_System_Threading_ThreadPool_GetAvailableThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
1475 ThreadPoolCounter counter;
1477 if (!worker_threads || !completion_port_threads)
1480 mono_lazy_initialize (&status, initialize);
1482 counter.as_gint64 = COUNTER_READ ();
1484 *worker_threads = MAX (0, threadpool->limit_worker_max - counter._.active);
1485 *completion_port_threads = threadpool->limit_io_max;
1489 ves_icall_System_Threading_ThreadPool_GetMinThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
1491 if (!worker_threads || !completion_port_threads)
1494 mono_lazy_initialize (&status, initialize);
1496 *worker_threads = threadpool->limit_worker_min;
1497 *completion_port_threads = threadpool->limit_io_min;
1501 ves_icall_System_Threading_ThreadPool_GetMaxThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
1503 if (!worker_threads || !completion_port_threads)
1506 mono_lazy_initialize (&status, initialize);
1508 *worker_threads = threadpool->limit_worker_max;
1509 *completion_port_threads = threadpool->limit_io_max;
1513 ves_icall_System_Threading_ThreadPool_SetMinThreadsNative (gint32 worker_threads, gint32 completion_port_threads)
1515 mono_lazy_initialize (&status, initialize);
1517 if (worker_threads <= 0 || worker_threads > threadpool->limit_worker_max)
1519 if (completion_port_threads <= 0 || completion_port_threads > threadpool->limit_io_max)
1522 threadpool->limit_worker_min = worker_threads;
1523 threadpool->limit_io_min = completion_port_threads;
1529 ves_icall_System_Threading_ThreadPool_SetMaxThreadsNative (gint32 worker_threads, gint32 completion_port_threads)
1531 gint cpu_count = mono_cpu_count ();
1533 mono_lazy_initialize (&status, initialize);
1535 if (worker_threads < threadpool->limit_worker_min || worker_threads < cpu_count)
1537 if (completion_port_threads < threadpool->limit_io_min || completion_port_threads < cpu_count)
1540 threadpool->limit_worker_max = worker_threads;
1541 threadpool->limit_io_max = completion_port_threads;
1547 ves_icall_System_Threading_ThreadPool_InitializeVMTp (MonoBoolean *enable_worker_tracking)
1549 if (enable_worker_tracking) {
1550 // TODO implement some kind of switch to have the possibily to use it
1551 *enable_worker_tracking = FALSE;
1554 mono_lazy_initialize (&status, initialize);
1558 ves_icall_System_Threading_ThreadPool_NotifyWorkItemComplete (void)
1560 ThreadPoolCounter counter;
1562 if (mono_domain_is_unloading (mono_domain_get ()) || mono_runtime_is_shutting_down ())
1565 heuristic_notify_work_completed ();
1567 if (heuristic_should_adjust ())
1568 heuristic_adjust ();
1570 counter.as_gint64 = COUNTER_READ ();
1571 return counter._.working <= counter._.max_working;
1575 ves_icall_System_Threading_ThreadPool_NotifyWorkItemProgressNative (void)
1577 heuristic_notify_work_completed ();
1579 if (heuristic_should_adjust ())
1580 heuristic_adjust ();
1584 ves_icall_System_Threading_ThreadPool_ReportThreadStatus (MonoBoolean is_working)
1587 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1591 ves_icall_System_Threading_ThreadPool_RequestWorkerThread (void)
1593 return worker_request (mono_domain_get ());
1596 MonoBoolean G_GNUC_UNUSED
1597 ves_icall_System_Threading_ThreadPool_PostQueuedCompletionStatus (MonoNativeOverlapped *native_overlapped)
1599 /* This copy the behavior of the current Mono implementation */
1600 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1604 MonoBoolean G_GNUC_UNUSED
1605 ves_icall_System_Threading_ThreadPool_BindIOCompletionCallbackNative (gpointer file_handle)
1607 /* This copy the behavior of the current Mono implementation */
1611 MonoBoolean G_GNUC_UNUSED
1612 ves_icall_System_Threading_ThreadPool_IsThreadPoolHosted (void)