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-internal.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/metadata/threadpool-internals.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-proclib.h>
40 #include <mono/utils/mono-threads.h>
41 #include <mono/utils/mono-time.h>
42 #include <mono/utils/mono-rand.h>
44 #define CPU_USAGE_LOW 80
45 #define CPU_USAGE_HIGH 95
47 #define MONITOR_INTERVAL 100 // ms
49 /* The exponent to apply to the gain. 1.0 means to use linear gain,
50 * higher values will enhance large moves and damp small ones.
52 #define HILL_CLIMBING_GAIN_EXPONENT 2.0
54 /* The 'cost' of a thread. 0 means drive for increased throughput regardless
55 * of thread count, higher values bias more against higher thread counts.
57 #define HILL_CLIMBING_BIAS 0.15
59 #define HILL_CLIMBING_WAVE_PERIOD 4
60 #define HILL_CLIMBING_MAX_WAVE_MAGNITUDE 20
61 #define HILL_CLIMBING_WAVE_MAGNITUDE_MULTIPLIER 1.0
62 #define HILL_CLIMBING_WAVE_HISTORY_SIZE 8
63 #define HILL_CLIMBING_TARGET_SIGNAL_TO_NOISE_RATIO 3.0
64 #define HILL_CLIMBING_MAX_CHANGE_PER_SECOND 4
65 #define HILL_CLIMBING_MAX_CHANGE_PER_SAMPLE 20
66 #define HILL_CLIMBING_SAMPLE_INTERVAL_LOW 10
67 #define HILL_CLIMBING_SAMPLE_INTERVAL_HIGH 200
68 #define HILL_CLIMBING_ERROR_SMOOTHING_FACTOR 0.01
69 #define HILL_CLIMBING_MAX_SAMPLE_ERROR_PERCENT 0.15
73 gint16 max_working; /* determined by heuristic */
74 gint16 active; /* executing worker_thread */
75 gint16 working; /* actively executing worker_thread, not parked */
76 gint16 parked; /* parked */
83 gint32 outstanding_request;
86 typedef MonoInternalThread ThreadPoolWorkingThread;
87 typedef mono_cond_t ThreadPoolParkedThread;
91 gint32 samples_to_measure;
92 gdouble target_throughput_ratio;
93 gdouble target_signal_to_noise_ratio;
94 gdouble max_change_per_second;
95 gdouble max_change_per_sample;
96 gint32 max_thread_wave_magnitude;
97 gint32 sample_interval_low;
98 gdouble thread_magnitude_multiplier;
99 gint32 sample_interval_high;
100 gdouble throughput_error_smoothing_factor;
101 gdouble gain_exponent;
102 gdouble max_sample_error;
104 gdouble current_control_setting;
105 gint64 total_samples;
106 gint16 last_thread_count;
107 gdouble elapsed_since_last_change;
108 gdouble completions_since_last_change;
110 gdouble average_throughput_noise;
113 gdouble *thread_counts;
115 guint32 current_sample_interval;
116 gpointer random_interval_generator;
118 gint32 accumulated_completion_count;
119 gdouble accumulated_sample_duration;
120 } ThreadPoolHillClimbing;
123 ThreadPoolCounter counters;
125 GPtrArray *domains; // ThreadPoolDomain* []
126 mono_mutex_t domains_lock;
128 GPtrArray *working_threads; // ThreadPoolWorkingThread* []
129 GPtrArray *parked_threads; // ThreadPoolParkedThread* []
130 mono_mutex_t active_threads_lock; /* protect access to working_threads and parked_threads */
132 gint32 heuristic_completions;
133 guint32 heuristic_sample_start;
134 guint32 heuristic_last_dequeue; // ms
135 guint32 heuristic_last_adjustment; // ms
136 guint32 heuristic_adjustment_interval; // ms
137 ThreadPoolHillClimbing heuristic_hill_climbing;
138 mono_mutex_t heuristic_lock;
140 gint32 limit_worker_min;
141 gint32 limit_worker_max;
145 MonoCpuUsageState *cpu_usage_state;
148 /* suspended by the debugger */
154 TRANSITION_INITIALIZING,
155 TRANSITION_RANDOM_MOVE,
156 TRANSITION_CLIMBING_MOVE,
157 TRANSITION_CHANGE_POINT,
158 TRANSITION_STABILIZING,
159 TRANSITION_STARVATION,
160 TRANSITION_THREAD_TIMED_OUT,
161 TRANSITION_UNDEFINED,
162 } ThreadPoolHeuristicStateTransition;
165 MONITOR_STATUS_REQUESTED,
166 MONITOR_STATUS_WAITING_FOR_REQUEST,
167 MONITOR_STATUS_NOT_RUNNING,
170 static gint32 status = STATUS_NOT_INITIALIZED;
171 static gint32 monitor_status = MONITOR_STATUS_NOT_RUNNING;
173 static ThreadPool* threadpool;
175 #define COUNTER_CHECK(counter) \
177 g_assert (counter._.max_working > 0); \
178 g_assert (counter._.working >= 0); \
179 g_assert (counter._.active >= 0); \
182 #define COUNTER_READ() (InterlockedRead64 (&threadpool->counters.as_gint64))
184 #define COUNTER_ATOMIC(var,block) \
186 ThreadPoolCounter __old; \
188 g_assert (threadpool); \
189 __old.as_gint64 = COUNTER_READ (); \
192 COUNTER_CHECK (var); \
193 } while (InterlockedCompareExchange64 (&threadpool->counters.as_gint64, (var).as_gint64, __old.as_gint64) != __old.as_gint64); \
196 #define COUNTER_TRY_ATOMIC(res,var,block) \
198 ThreadPoolCounter __old; \
200 g_assert (threadpool); \
201 __old.as_gint64 = COUNTER_READ (); \
205 COUNTER_CHECK (var); \
206 (res) = InterlockedCompareExchange64 (&threadpool->counters.as_gint64, (var).as_gint64, __old.as_gint64) == __old.as_gint64; \
214 return mono_rand_init (NULL, 0);
218 rand_next (gpointer *handle, guint32 min, guint32 max)
221 if (!mono_rand_try_get_uint32 (handle, &val, min, max)) {
222 // FIXME handle error
223 g_assert_not_reached ();
229 rand_free (gpointer handle)
231 mono_rand_close (handle);
235 ensure_initialized (MonoBoolean *enable_worker_tracking)
237 ThreadPoolHillClimbing *hc;
238 const char *threads_per_cpu_env;
239 gint threads_per_cpu;
242 if (enable_worker_tracking) {
243 // TODO implement some kind of switch to have the possibily to use it
244 *enable_worker_tracking = FALSE;
247 if (status >= STATUS_INITIALIZED)
249 if (status == STATUS_INITIALIZING || InterlockedCompareExchange (&status, STATUS_INITIALIZING, STATUS_NOT_INITIALIZED) != STATUS_NOT_INITIALIZED) {
250 while (status == STATUS_INITIALIZING)
251 mono_thread_info_yield ();
252 g_assert (status >= STATUS_INITIALIZED);
256 g_assert (!threadpool);
257 threadpool = g_new0 (ThreadPool, 1);
258 g_assert (threadpool);
260 threadpool->domains = g_ptr_array_new ();
261 mono_mutex_init_recursive (&threadpool->domains_lock);
263 threadpool->parked_threads = g_ptr_array_new ();
264 threadpool->working_threads = g_ptr_array_new ();
265 mono_mutex_init (&threadpool->active_threads_lock);
267 threadpool->heuristic_adjustment_interval = 10;
268 mono_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;
307 threadpool->limit_worker_max = threadpool->limit_io_max = threads_count * 100;
309 threadpool->counters._.max_working = threadpool->limit_worker_min;
311 threadpool->cpu_usage_state = g_new0 (MonoCpuUsageState, 1);
313 threadpool->suspended = FALSE;
315 status = STATUS_INITIALIZED;
318 static void worker_unpark (ThreadPoolParkedThread *thread);
319 static void worker_kill (ThreadPoolWorkingThread *thread);
322 ensure_cleanedup (void)
326 if (status == STATUS_NOT_INITIALIZED && InterlockedCompareExchange (&status, STATUS_CLEANED_UP, STATUS_NOT_INITIALIZED) == STATUS_NOT_INITIALIZED)
328 if (status == STATUS_INITIALIZING) {
329 while (status == STATUS_INITIALIZING)
330 mono_thread_info_yield ();
332 if (status == STATUS_CLEANED_UP)
334 if (status == STATUS_CLEANING_UP || InterlockedCompareExchange (&status, STATUS_CLEANING_UP, STATUS_INITIALIZED) != STATUS_INITIALIZED) {
335 while (status == STATUS_CLEANING_UP)
336 mono_thread_info_yield ();
337 g_assert (status == STATUS_CLEANED_UP);
341 /* we make the assumption along the code that we are
342 * cleaning up only if the runtime is shutting down */
343 g_assert (mono_runtime_is_shutting_down ());
345 while (monitor_status != MONITOR_STATUS_NOT_RUNNING)
348 mono_mutex_lock (&threadpool->active_threads_lock);
350 /* stop all threadpool->working_threads */
351 for (i = 0; i < threadpool->working_threads->len; ++i)
352 worker_kill ((ThreadPoolWorkingThread*) g_ptr_array_index (threadpool->working_threads, i));
354 /* unpark all threadpool->parked_threads */
355 for (i = 0; i < threadpool->parked_threads->len; ++i)
356 worker_unpark ((ThreadPoolParkedThread*) g_ptr_array_index (threadpool->parked_threads, i));
358 mono_mutex_unlock (&threadpool->active_threads_lock);
360 status = STATUS_CLEANED_UP;
364 mono_threadpool_ms_enqueue_work_item (MonoDomain *domain, MonoObject *work_item)
366 static MonoClass *threadpool_class = NULL;
367 static MonoMethod *unsafe_queue_custom_work_item_method = NULL;
368 MonoDomain *current_domain;
372 g_assert (work_item);
374 if (!threadpool_class)
375 threadpool_class = mono_class_from_name (mono_defaults.corlib, "System.Threading", "ThreadPool");
376 g_assert (threadpool_class);
378 if (!unsafe_queue_custom_work_item_method)
379 unsafe_queue_custom_work_item_method = mono_class_get_method_from_name (threadpool_class, "UnsafeQueueCustomWorkItem", 2);
380 g_assert (unsafe_queue_custom_work_item_method);
384 args [0] = (gpointer) work_item;
385 args [1] = (gpointer) &f;
387 current_domain = mono_domain_get ();
388 if (current_domain == domain) {
389 mono_runtime_invoke (unsafe_queue_custom_work_item_method, NULL, args, NULL);
391 mono_thread_push_appdomain_ref (domain);
392 if (mono_domain_set (domain, FALSE)) {
393 mono_runtime_invoke (unsafe_queue_custom_work_item_method, NULL, args, NULL);
394 mono_domain_set (current_domain, TRUE);
396 mono_thread_pop_appdomain_ref ();
401 domain_add (ThreadPoolDomain *tpdomain)
407 mono_mutex_lock (&threadpool->domains_lock);
408 len = threadpool->domains->len;
409 for (i = 0; i < len; ++i) {
410 if (g_ptr_array_index (threadpool->domains, i) == tpdomain)
414 g_ptr_array_add (threadpool->domains, tpdomain);
415 mono_mutex_unlock (&threadpool->domains_lock);
419 domain_remove (ThreadPoolDomain *tpdomain)
425 mono_mutex_lock (&threadpool->domains_lock);
426 res = g_ptr_array_remove (threadpool->domains, tpdomain);
427 mono_mutex_unlock (&threadpool->domains_lock);
432 static ThreadPoolDomain *
433 domain_get (MonoDomain *domain, gboolean create)
435 ThreadPoolDomain *tpdomain = NULL;
440 mono_mutex_lock (&threadpool->domains_lock);
441 for (i = 0; i < threadpool->domains->len; ++i) {
442 ThreadPoolDomain *tmp = g_ptr_array_index (threadpool->domains, i);
443 if (tmp->domain == domain) {
448 if (!tpdomain && create) {
449 tpdomain = g_new0 (ThreadPoolDomain, 1);
450 tpdomain->domain = domain;
451 domain_add (tpdomain);
453 mono_mutex_unlock (&threadpool->domains_lock);
458 domain_free (ThreadPoolDomain *tpdomain)
464 domain_any_has_request (void)
466 gboolean res = FALSE;
469 mono_mutex_lock (&threadpool->domains_lock);
470 for (i = 0; i < threadpool->domains->len; ++i) {
471 ThreadPoolDomain *tmp = g_ptr_array_index (threadpool->domains, i);
472 if (tmp->outstanding_request > 0) {
477 mono_mutex_unlock (&threadpool->domains_lock);
481 static ThreadPoolDomain *
482 domain_get_next (ThreadPoolDomain *current)
484 ThreadPoolDomain *tpdomain = NULL;
487 mono_mutex_lock (&threadpool->domains_lock);
488 len = threadpool->domains->len;
490 guint i, current_idx = -1;
492 for (i = 0; i < len; ++i) {
493 if (current == g_ptr_array_index (threadpool->domains, i)) {
498 g_assert (current_idx >= 0);
500 for (i = current_idx + 1; i < len + current_idx + 1; ++i) {
501 ThreadPoolDomain *tmp = g_ptr_array_index (threadpool->domains, i % len);
502 if (tmp->outstanding_request > 0) {
508 mono_mutex_unlock (&threadpool->domains_lock);
516 MonoInternalThread *thread = mono_thread_internal_current ();
518 mono_cond_init (&cond, NULL);
520 mono_gc_set_skip_thread (TRUE);
522 mono_mutex_lock (&threadpool->active_threads_lock);
524 if (!mono_runtime_is_shutting_down ()) {
525 g_ptr_array_add (threadpool->parked_threads, &cond);
526 g_ptr_array_remove_fast (threadpool->working_threads, thread);
528 mono_cond_wait (&cond, &threadpool->active_threads_lock);
530 g_ptr_array_add (threadpool->working_threads, thread);
531 g_ptr_array_remove (threadpool->parked_threads, &cond);
534 mono_mutex_unlock (&threadpool->active_threads_lock);
536 mono_gc_set_skip_thread (FALSE);
538 mono_cond_destroy (&cond);
542 worker_try_unpark (void)
544 gboolean res = FALSE;
547 mono_mutex_lock (&threadpool->active_threads_lock);
548 len = threadpool->parked_threads->len;
550 mono_cond_t *cond = (mono_cond_t*) g_ptr_array_index (threadpool->parked_threads, len - 1);
551 mono_cond_signal (cond);
554 mono_mutex_unlock (&threadpool->active_threads_lock);
559 worker_unpark (ThreadPoolParkedThread *thread)
561 mono_cond_signal ((mono_cond_t*) thread);
565 worker_kill (ThreadPoolWorkingThread *thread)
567 if (thread == mono_thread_internal_current ())
570 mono_thread_internal_stop ((MonoInternalThread*) thread);
574 worker_thread (gpointer data)
576 static MonoClass *threadpool_wait_callback_class = NULL;
577 static MonoMethod *perform_wait_callback_method = NULL;
578 MonoInternalThread *thread;
579 ThreadPoolDomain *tpdomain, *previous_tpdomain;
580 ThreadPoolCounter counter;
581 gboolean retire = FALSE;
583 g_assert (status >= STATUS_INITIALIZED);
585 if (!threadpool_wait_callback_class)
586 threadpool_wait_callback_class = mono_class_from_name (mono_defaults.corlib, "System.Threading.Microsoft", "_ThreadPoolWaitCallback");
587 g_assert (threadpool_wait_callback_class);
589 if (!perform_wait_callback_method)
590 perform_wait_callback_method = mono_class_get_method_from_name (threadpool_wait_callback_class, "PerformWaitCallback", 0);
591 g_assert (perform_wait_callback_method);
593 g_assert (threadpool);
595 thread = mono_thread_internal_current ();
598 mono_thread_set_name_internal (thread, mono_string_new (mono_domain_get (), "Threadpool worker"), FALSE);
600 mono_mutex_lock (&threadpool->active_threads_lock);
601 g_ptr_array_add (threadpool->working_threads, thread);
602 mono_mutex_unlock (&threadpool->active_threads_lock);
604 previous_tpdomain = NULL;
606 mono_mutex_lock (&threadpool->domains_lock);
608 while (!mono_runtime_is_shutting_down ()) {
611 if ((thread->state & (ThreadState_StopRequested | ThreadState_SuspendRequested)) != 0) {
612 mono_mutex_unlock (&threadpool->domains_lock);
613 mono_thread_interruption_checkpoint ();
614 mono_mutex_lock (&threadpool->domains_lock);
617 if (retire || !(tpdomain = domain_get_next (previous_tpdomain))) {
618 COUNTER_ATOMIC (counter, {
619 counter._.working --;
623 mono_mutex_unlock (&threadpool->domains_lock);
625 mono_mutex_lock (&threadpool->domains_lock);
627 COUNTER_ATOMIC (counter, {
628 counter._.working ++;
638 tpdomain->outstanding_request --;
639 g_assert (tpdomain->outstanding_request >= 0);
641 g_assert (tpdomain->domain);
642 g_assert (tpdomain->domain->threadpool_jobs >= 0);
643 tpdomain->domain->threadpool_jobs ++;
645 mono_mutex_unlock (&threadpool->domains_lock);
647 mono_thread_push_appdomain_ref (tpdomain->domain);
648 if (mono_domain_set (tpdomain->domain, FALSE)) {
649 MonoObject *exc = NULL;
650 MonoObject *res = mono_runtime_invoke (perform_wait_callback_method, NULL, NULL, &exc);
652 mono_internal_thread_unhandled_exception (exc);
653 else if (res && *(MonoBoolean*) mono_object_unbox (res) == FALSE)
656 mono_thread_clr_state (thread , ~ThreadState_Background);
657 if (!mono_thread_test_state (thread , ThreadState_Background))
658 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
660 mono_domain_set (mono_get_root_domain (), TRUE);
662 mono_thread_pop_appdomain_ref ();
664 mono_mutex_lock (&threadpool->domains_lock);
666 tpdomain->domain->threadpool_jobs --;
667 g_assert (tpdomain->domain->threadpool_jobs >= 0);
669 if (tpdomain->domain->threadpool_jobs == 0 && mono_domain_is_unloading (tpdomain->domain)) {
670 gboolean removed = domain_remove (tpdomain);
672 if (tpdomain->domain->cleanup_semaphore)
673 ReleaseSemaphore (tpdomain->domain->cleanup_semaphore, 1, NULL);
674 domain_free (tpdomain);
678 previous_tpdomain = tpdomain;
681 mono_mutex_unlock (&threadpool->domains_lock);
683 mono_mutex_lock (&threadpool->active_threads_lock);
684 g_ptr_array_remove_fast (threadpool->working_threads, thread);
685 mono_mutex_unlock (&threadpool->active_threads_lock);
687 COUNTER_ATOMIC (counter, {
694 worker_try_create (void)
696 ThreadPoolCounter counter;
698 COUNTER_ATOMIC (counter, {
699 if (counter._.working >= counter._.max_working)
701 counter._.working ++;
705 if (mono_thread_create_internal (mono_get_root_domain (), worker_thread, NULL, TRUE, 0) != NULL)
708 COUNTER_ATOMIC (counter, {
709 counter._.working --;
716 static void monitor_ensure_running (void);
719 worker_request (MonoDomain *domain)
721 ThreadPoolDomain *tpdomain;
724 g_assert (threadpool);
726 if (mono_runtime_is_shutting_down ())
729 mono_mutex_lock (&threadpool->domains_lock);
731 /* synchronize check with worker_thread */
732 if (mono_domain_is_unloading (domain)) {
733 mono_mutex_unlock (&threadpool->domains_lock);
737 tpdomain = domain_get (domain, TRUE);
739 tpdomain->outstanding_request ++;
741 mono_mutex_unlock (&threadpool->domains_lock);
743 if (threadpool->suspended)
746 monitor_ensure_running ();
748 if (worker_try_unpark ())
751 if (worker_try_create ())
758 monitor_should_keep_running (void)
760 g_assert (monitor_status == MONITOR_STATUS_WAITING_FOR_REQUEST || monitor_status == MONITOR_STATUS_REQUESTED);
762 if (InterlockedExchange (&monitor_status, MONITOR_STATUS_WAITING_FOR_REQUEST) == MONITOR_STATUS_WAITING_FOR_REQUEST) {
763 if (mono_runtime_is_shutting_down () || !domain_any_has_request ()) {
764 if (InterlockedCompareExchange (&monitor_status, MONITOR_STATUS_NOT_RUNNING, MONITOR_STATUS_WAITING_FOR_REQUEST) == MONITOR_STATUS_WAITING_FOR_REQUEST)
769 g_assert (monitor_status == MONITOR_STATUS_WAITING_FOR_REQUEST || monitor_status == MONITOR_STATUS_REQUESTED);
775 monitor_sufficient_delay_since_last_dequeue (void)
779 g_assert (threadpool);
781 if (threadpool->cpu_usage < CPU_USAGE_LOW) {
782 threshold = MONITOR_INTERVAL;
784 ThreadPoolCounter counter;
785 counter.as_gint64 = COUNTER_READ();
786 threshold = counter._.max_working * MONITOR_INTERVAL * 2;
789 return mono_msec_ticks () >= threadpool->heuristic_last_dequeue + threshold;
792 static void hill_climbing_force_change (gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition);
795 monitor_thread (void)
797 MonoInternalThread *current_thread = mono_thread_internal_current ();
800 mono_cpu_usage (threadpool->cpu_usage_state);
803 MonoInternalThread *thread;
804 gboolean all_waitsleepjoin = TRUE;
805 gint32 interval_left = MONITOR_INTERVAL;
806 gint32 awake = 0; /* number of spurious awakes we tolerate before doing a round of rebalancing */
808 g_assert (monitor_status != MONITOR_STATUS_NOT_RUNNING);
810 mono_gc_set_skip_thread (TRUE);
815 if (mono_runtime_is_shutting_down ())
818 ts = mono_msec_ticks ();
819 if (SleepEx (interval_left, TRUE) == 0)
821 interval_left -= mono_msec_ticks () - ts;
823 mono_gc_set_skip_thread (FALSE);
824 if ((current_thread->state & (ThreadState_StopRequested | ThreadState_SuspendRequested)) != 0)
825 mono_thread_interruption_checkpoint ();
826 mono_gc_set_skip_thread (TRUE);
827 } while (interval_left > 0 && ++awake < 10);
829 mono_gc_set_skip_thread (FALSE);
831 if (threadpool->suspended)
834 if (mono_runtime_is_shutting_down () || !domain_any_has_request ())
837 mono_mutex_lock (&threadpool->active_threads_lock);
838 for (i = 0; i < threadpool->working_threads->len; ++i) {
839 thread = g_ptr_array_index (threadpool->working_threads, i);
840 if ((thread->state & ThreadState_WaitSleepJoin) == 0) {
841 all_waitsleepjoin = FALSE;
845 mono_mutex_unlock (&threadpool->active_threads_lock);
847 if (all_waitsleepjoin) {
848 ThreadPoolCounter counter;
849 COUNTER_ATOMIC (counter, { counter._.max_working ++; });
850 hill_climbing_force_change (counter._.max_working, TRANSITION_STARVATION);
853 threadpool->cpu_usage = mono_cpu_usage (threadpool->cpu_usage_state);
855 if (monitor_sufficient_delay_since_last_dequeue ()) {
856 for (i = 0; i < 5; ++i) {
857 if (mono_runtime_is_shutting_down ())
860 if (worker_try_unpark ())
863 if (worker_try_create ())
867 } while (monitor_should_keep_running ());
871 monitor_ensure_running (void)
874 switch (monitor_status) {
875 case MONITOR_STATUS_REQUESTED:
877 case MONITOR_STATUS_WAITING_FOR_REQUEST:
878 InterlockedCompareExchange (&monitor_status, MONITOR_STATUS_REQUESTED, MONITOR_STATUS_WAITING_FOR_REQUEST);
880 case MONITOR_STATUS_NOT_RUNNING:
881 if (mono_runtime_is_shutting_down ())
883 if (InterlockedCompareExchange (&monitor_status, MONITOR_STATUS_REQUESTED, MONITOR_STATUS_NOT_RUNNING) == MONITOR_STATUS_NOT_RUNNING) {
884 if (!mono_thread_create_internal (mono_get_root_domain (), monitor_thread, NULL, TRUE, SMALL_STACK))
885 monitor_status = MONITOR_STATUS_NOT_RUNNING;
889 default: g_assert_not_reached ();
895 hill_climbing_change_thread_count (gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition)
897 ThreadPoolHillClimbing *hc;
899 g_assert (threadpool);
901 hc = &threadpool->heuristic_hill_climbing;
903 hc->last_thread_count = new_thread_count;
904 hc->current_sample_interval = rand_next (&hc->random_interval_generator, hc->sample_interval_low, hc->sample_interval_high);
905 hc->elapsed_since_last_change = 0;
906 hc->completions_since_last_change = 0;
910 hill_climbing_force_change (gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition)
912 ThreadPoolHillClimbing *hc;
914 g_assert (threadpool);
916 hc = &threadpool->heuristic_hill_climbing;
918 if (new_thread_count != hc->last_thread_count) {
919 hc->current_control_setting += new_thread_count - hc->last_thread_count;
920 hill_climbing_change_thread_count (new_thread_count, transition);
924 static double_complex
925 hill_climbing_get_wave_component (gdouble *samples, guint sample_count, gdouble period)
927 ThreadPoolHillClimbing *hc;
928 gdouble w, cosine, sine, coeff, q0, q1, q2;
931 g_assert (threadpool);
932 g_assert (sample_count >= period);
933 g_assert (period >= 2);
935 hc = &threadpool->heuristic_hill_climbing;
937 w = 2.0 * M_PI / period;
940 coeff = 2.0 * cosine;
943 for (i = 0; i < sample_count; ++i) {
944 q0 = coeff * q1 - q2 + samples [(hc->total_samples - sample_count + i) % hc->samples_to_measure];
949 return mono_double_complex_scalar_div (mono_double_complex_make (q1 - q2 * cosine, (q2 * sine)), ((gdouble)sample_count));
953 hill_climbing_update (gint16 current_thread_count, guint32 sample_duration, gint32 completions, guint32 *adjustment_interval)
955 ThreadPoolHillClimbing *hc;
956 ThreadPoolHeuristicStateTransition transition;
958 gdouble throughput_error_estimate;
964 gint new_thread_wave_magnitude;
965 gint new_thread_count;
966 double_complex thread_wave_component;
967 double_complex throughput_wave_component;
968 double_complex ratio;
970 g_assert (threadpool);
971 g_assert (adjustment_interval);
973 hc = &threadpool->heuristic_hill_climbing;
975 /* If someone changed the thread count without telling us, update our records accordingly. */
976 if (current_thread_count != hc->last_thread_count)
977 hill_climbing_force_change (current_thread_count, TRANSITION_INITIALIZING);
979 /* Update the cumulative stats for this thread count */
980 hc->elapsed_since_last_change += sample_duration;
981 hc->completions_since_last_change += completions;
983 /* Add in any data we've already collected about this sample */
984 sample_duration += hc->accumulated_sample_duration;
985 completions += hc->accumulated_completion_count;
987 /* We need to make sure we're collecting reasonably accurate data. Since we're just counting the end
988 * of each work item, we are goinng to be missing some data about what really happened during the
989 * sample interval. The count produced by each thread includes an initial work item that may have
990 * started well before the start of the interval, and each thread may have been running some new
991 * work item for some time before the end of the interval, which did not yet get counted. So
992 * our count is going to be off by +/- threadCount workitems.
994 * The exception is that the thread that reported to us last time definitely wasn't running any work
995 * at that time, and the thread that's reporting now definitely isn't running a work item now. So
996 * we really only need to consider threadCount-1 threads.
998 * Thus the percent error in our count is +/- (threadCount-1)/numCompletions.
1000 * We cannot rely on the frequency-domain analysis we'll be doing later to filter out this error, because
1001 * of the way it accumulates over time. If this sample is off by, say, 33% in the negative direction,
1002 * then the next one likely will be too. The one after that will include the sum of the completions
1003 * we missed in the previous samples, and so will be 33% positive. So every three samples we'll have
1004 * two "low" samples and one "high" sample. This will appear as periodic variation right in the frequency
1005 * range we're targeting, which will not be filtered by the frequency-domain translation. */
1006 if (hc->total_samples > 0 && ((current_thread_count - 1.0) / completions) >= hc->max_sample_error) {
1007 /* Not accurate enough yet. Let's accumulate the data so
1008 * far, and tell the ThreadPool to collect a little more. */
1009 hc->accumulated_sample_duration = sample_duration;
1010 hc->accumulated_completion_count = completions;
1011 *adjustment_interval = 10;
1012 return current_thread_count;
1015 /* We've got enouugh data for our sample; reset our accumulators for next time. */
1016 hc->accumulated_sample_duration = 0;
1017 hc->accumulated_completion_count = 0;
1019 /* Add the current thread count and throughput sample to our history. */
1020 throughput = ((gdouble) completions) / sample_duration;
1022 sample_index = hc->total_samples % hc->samples_to_measure;
1023 hc->samples [sample_index] = throughput;
1024 hc->thread_counts [sample_index] = current_thread_count;
1025 hc->total_samples ++;
1027 /* Set up defaults for our metrics. */
1028 thread_wave_component = mono_double_complex_make(0, 0);
1029 throughput_wave_component = mono_double_complex_make(0, 0);
1030 throughput_error_estimate = 0;
1031 ratio = mono_double_complex_make(0, 0);
1034 transition = TRANSITION_WARMUP;
1036 /* How many samples will we use? It must be at least the three wave periods we're looking for, and it must also
1037 * be a whole multiple of the primary wave's period; otherwise the frequency we're looking for will fall between
1038 * two frequency bands in the Fourier analysis, and we won't be able to measure it accurately. */
1039 sample_count = ((gint) MIN (hc->total_samples - 1, hc->samples_to_measure) / hc->wave_period) * hc->wave_period;
1041 if (sample_count > hc->wave_period) {
1043 gdouble average_throughput;
1044 gdouble average_thread_count;
1045 gdouble sample_sum = 0;
1046 gdouble thread_sum = 0;
1048 /* Average the throughput and thread count samples, so we can scale the wave magnitudes later. */
1049 for (i = 0; i < sample_count; ++i) {
1050 guint j = (hc->total_samples - sample_count + i) % hc->samples_to_measure;
1051 sample_sum += hc->samples [j];
1052 thread_sum += hc->thread_counts [j];
1055 average_throughput = sample_sum / sample_count;
1056 average_thread_count = thread_sum / sample_count;
1058 if (average_throughput > 0 && average_thread_count > 0) {
1059 gdouble noise_for_confidence, adjacent_period_1, adjacent_period_2;
1061 /* Calculate the periods of the adjacent frequency bands we'll be using to
1062 * measure noise levels. We want the two adjacent Fourier frequency bands. */
1063 adjacent_period_1 = sample_count / (((gdouble) sample_count) / ((gdouble) hc->wave_period) + 1);
1064 adjacent_period_2 = sample_count / (((gdouble) sample_count) / ((gdouble) hc->wave_period) - 1);
1066 /* Get the the three different frequency components of the throughput (scaled by average
1067 * throughput). Our "error" estimate (the amount of noise that might be present in the
1068 * frequency band we're really interested in) is the average of the adjacent bands. */
1069 throughput_wave_component = mono_double_complex_scalar_div (hill_climbing_get_wave_component (hc->samples, sample_count, hc->wave_period), average_throughput);
1070 throughput_error_estimate = cabs (mono_double_complex_scalar_div (hill_climbing_get_wave_component (hc->samples, sample_count, adjacent_period_1), average_throughput));
1072 if (adjacent_period_2 <= sample_count) {
1073 throughput_error_estimate = MAX (throughput_error_estimate, cabs (mono_double_complex_scalar_div (hill_climbing_get_wave_component (
1074 hc->samples, sample_count, adjacent_period_2), average_throughput)));
1077 /* Do the same for the thread counts, so we have something to compare to. We don't
1078 * measure thread count noise, because there is none; these are exact measurements. */
1079 thread_wave_component = mono_double_complex_scalar_div (hill_climbing_get_wave_component (hc->thread_counts, sample_count, hc->wave_period), average_thread_count);
1081 /* Update our moving average of the throughput noise. We'll use this
1082 * later as feedback to determine the new size of the thread wave. */
1083 if (hc->average_throughput_noise == 0) {
1084 hc->average_throughput_noise = throughput_error_estimate;
1086 hc->average_throughput_noise = (hc->throughput_error_smoothing_factor * throughput_error_estimate)
1087 + ((1.0 + hc->throughput_error_smoothing_factor) * hc->average_throughput_noise);
1090 if (cabs (thread_wave_component) > 0) {
1091 /* Adjust the throughput wave so it's centered around the target wave,
1092 * and then calculate the adjusted throughput/thread ratio. */
1093 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);
1094 transition = TRANSITION_CLIMBING_MOVE;
1096 ratio = mono_double_complex_make (0, 0);
1097 transition = TRANSITION_STABILIZING;
1100 noise_for_confidence = MAX (hc->average_throughput_noise, throughput_error_estimate);
1101 if (noise_for_confidence > 0) {
1102 confidence = cabs (thread_wave_component) / noise_for_confidence / hc->target_signal_to_noise_ratio;
1104 /* there is no noise! */
1110 /* We use just the real part of the complex ratio we just calculated. If the throughput signal
1111 * is exactly in phase with the thread signal, this will be the same as taking the magnitude of
1112 * the complex move and moving that far up. If they're 180 degrees out of phase, we'll move
1113 * backward (because this indicates that our changes are having the opposite of the intended effect).
1114 * If they're 90 degrees out of phase, we won't move at all, because we can't tell wether we're
1115 * having a negative or positive effect on throughput. */
1116 move = creal (ratio);
1117 move = CLAMP (move, -1.0, 1.0);
1119 /* Apply our confidence multiplier. */
1120 move *= CLAMP (confidence, -1.0, 1.0);
1122 /* Now apply non-linear gain, such that values around zero are attenuated, while higher values
1123 * are enhanced. This allows us to move quickly if we're far away from the target, but more slowly
1124 * if we're getting close, giving us rapid ramp-up without wild oscillations around the target. */
1125 gain = hc->max_change_per_second * sample_duration;
1126 move = pow (fabs (move), hc->gain_exponent) * (move >= 0.0 ? 1 : -1) * gain;
1127 move = MIN (move, hc->max_change_per_sample);
1129 /* If the result was positive, and CPU is > 95%, refuse the move. */
1130 if (move > 0.0 && threadpool->cpu_usage > CPU_USAGE_HIGH)
1133 /* Apply the move to our control setting. */
1134 hc->current_control_setting += move;
1136 /* Calculate the new thread wave magnitude, which is based on the moving average we've been keeping of the
1137 * throughput error. This average starts at zero, so we'll start with a nice safe little wave at first. */
1138 new_thread_wave_magnitude = (gint)(0.5 + (hc->current_control_setting * hc->average_throughput_noise
1139 * hc->target_signal_to_noise_ratio * hc->thread_magnitude_multiplier * 2.0));
1140 new_thread_wave_magnitude = CLAMP (new_thread_wave_magnitude, 1, hc->max_thread_wave_magnitude);
1142 /* Make sure our control setting is within the ThreadPool's limits. */
1143 hc->current_control_setting = CLAMP (hc->current_control_setting, threadpool->limit_worker_min, threadpool->limit_worker_max - new_thread_wave_magnitude);
1145 /* Calculate the new thread count (control setting + square wave). */
1146 new_thread_count = (gint)(hc->current_control_setting + new_thread_wave_magnitude * ((hc->total_samples / (hc->wave_period / 2)) % 2));
1148 /* Make sure the new thread count doesn't exceed the ThreadPool's limits. */
1149 new_thread_count = CLAMP (new_thread_count, threadpool->limit_worker_min, threadpool->limit_worker_max);
1151 if (new_thread_count != current_thread_count)
1152 hill_climbing_change_thread_count (new_thread_count, transition);
1154 if (creal (ratio) < 0.0 && new_thread_count == threadpool->limit_worker_min)
1155 *adjustment_interval = (gint)(0.5 + hc->current_sample_interval * (10.0 * MAX (-1.0 * creal (ratio), 1.0)));
1157 *adjustment_interval = hc->current_sample_interval;
1159 return new_thread_count;
1163 heuristic_notify_work_completed (void)
1165 g_assert (threadpool);
1167 InterlockedIncrement (&threadpool->heuristic_completions);
1168 threadpool->heuristic_last_dequeue = mono_msec_ticks ();
1172 heuristic_should_adjust (void)
1174 g_assert (threadpool);
1176 if (threadpool->heuristic_last_dequeue > threadpool->heuristic_last_adjustment + threadpool->heuristic_adjustment_interval) {
1177 ThreadPoolCounter counter;
1178 counter.as_gint64 = COUNTER_READ();
1179 if (counter._.working <= counter._.max_working)
1187 heuristic_adjust (void)
1189 g_assert (threadpool);
1191 if (mono_mutex_trylock (&threadpool->heuristic_lock) == 0) {
1192 gint32 completions = InterlockedExchange (&threadpool->heuristic_completions, 0);
1193 guint32 sample_end = mono_msec_ticks ();
1194 guint32 sample_duration = sample_end - threadpool->heuristic_sample_start;
1196 if (sample_duration >= threadpool->heuristic_adjustment_interval / 2) {
1197 ThreadPoolCounter counter;
1198 gint16 new_thread_count;
1200 counter.as_gint64 = COUNTER_READ ();
1201 new_thread_count = hill_climbing_update (counter._.max_working, sample_duration, completions, &threadpool->heuristic_adjustment_interval);
1203 COUNTER_ATOMIC (counter, { counter._.max_working = new_thread_count; });
1205 if (new_thread_count > counter._.max_working)
1206 worker_request (mono_domain_get ());
1208 threadpool->heuristic_sample_start = sample_end;
1209 threadpool->heuristic_last_adjustment = mono_msec_ticks ();
1212 mono_mutex_unlock (&threadpool->heuristic_lock);
1217 mono_threadpool_ms_cleanup (void)
1219 #ifndef DISABLE_SOCKETS
1220 mono_threadpool_ms_io_cleanup ();
1222 ensure_cleanedup ();
1226 mono_threadpool_ms_begin_invoke (MonoDomain *domain, MonoObject *target, MonoMethod *method, gpointer *params)
1228 static MonoClass *async_call_klass = NULL;
1229 MonoMethodMessage *message;
1230 MonoAsyncResult *async_result;
1231 MonoAsyncCall *async_call;
1232 MonoDelegate *async_callback = NULL;
1233 MonoObject *state = NULL;
1235 if (!async_call_klass)
1236 async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
1237 g_assert (async_call_klass);
1239 ensure_initialized (NULL);
1241 message = mono_method_call_message_new (method, params, mono_get_delegate_invoke (method->klass), (params != NULL) ? (&async_callback) : NULL, (params != NULL) ? (&state) : NULL);
1243 async_call = (MonoAsyncCall*) mono_object_new (domain, async_call_klass);
1244 MONO_OBJECT_SETREF (async_call, msg, message);
1245 MONO_OBJECT_SETREF (async_call, state, state);
1247 if (async_callback) {
1248 MONO_OBJECT_SETREF (async_call, cb_method, mono_get_delegate_invoke (((MonoObject*) async_callback)->vtable->klass));
1249 MONO_OBJECT_SETREF (async_call, cb_target, async_callback);
1252 async_result = mono_async_result_new (domain, NULL, async_call->state, NULL, (MonoObject*) async_call);
1253 MONO_OBJECT_SETREF (async_result, async_delegate, target);
1255 #ifndef DISABLE_SOCKETS
1256 if (mono_threadpool_ms_is_io (target, state))
1257 return mono_threadpool_ms_io_add (async_result, (MonoSocketAsyncResult*) state);
1260 mono_threadpool_ms_enqueue_work_item (domain, (MonoObject*) async_result);
1262 return async_result;
1266 mono_threadpool_ms_end_invoke (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1271 g_assert (out_args);
1276 /* check if already finished */
1277 mono_monitor_enter ((MonoObject*) ares);
1279 if (ares->endinvoke_called) {
1280 *exc = (MonoObject*) mono_get_exception_invalid_operation (NULL);
1281 mono_monitor_exit ((MonoObject*) ares);
1285 MONO_OBJECT_SETREF (ares, endinvoke_called, 1);
1287 /* wait until we are really finished */
1288 if (ares->completed) {
1289 mono_monitor_exit ((MonoObject *) ares);
1291 gpointer wait_event;
1293 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle*) ares->handle);
1295 wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1296 g_assert(wait_event);
1297 MONO_OBJECT_SETREF (ares, handle, (MonoObject*) mono_wait_handle_new (mono_object_domain (ares), wait_event));
1299 mono_monitor_exit ((MonoObject*) ares);
1300 MONO_PREPARE_BLOCKING
1301 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
1302 MONO_FINISH_BLOCKING
1305 ac = (MonoAsyncCall*) ares->object_data;
1308 *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1309 *out_args = ac->out_args;
1314 mono_threadpool_ms_remove_domain_jobs (MonoDomain *domain, int timeout)
1316 gboolean res = TRUE;
1321 g_assert (timeout >= -1);
1323 g_assert (mono_domain_is_unloading (domain));
1326 start = mono_msec_ticks ();
1328 #ifndef DISABLE_SOCKETS
1329 mono_threadpool_ms_io_remove_domain_jobs (domain);
1330 if (timeout != -1) {
1331 timeout -= mono_msec_ticks () - start;
1338 * There might be some threads out that could be about to execute stuff from the given domain.
1339 * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
1341 sem = domain->cleanup_semaphore = CreateSemaphore (NULL, 0, 1, NULL);
1344 * The memory barrier here is required to have global ordering between assigning to cleanup_semaphone
1345 * and reading threadpool_jobs. Otherwise this thread could read a stale version of threadpool_jobs
1348 mono_memory_write_barrier ();
1350 while (domain->threadpool_jobs) {
1351 MONO_PREPARE_BLOCKING
1352 WaitForSingleObject (sem, timeout);
1353 MONO_FINISH_BLOCKING
1354 if (timeout != -1) {
1355 timeout -= mono_msec_ticks () - start;
1363 domain->cleanup_semaphore = NULL;
1370 mono_threadpool_ms_suspend (void)
1372 threadpool->suspended = TRUE;
1376 mono_threadpool_ms_resume (void)
1378 threadpool->suspended = FALSE;
1382 ves_icall_System_Threading_Microsoft_ThreadPool_GetAvailableThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
1384 if (!worker_threads || !completion_port_threads)
1387 ensure_initialized (NULL);
1389 *worker_threads = threadpool->limit_worker_max;
1390 *completion_port_threads = threadpool->limit_io_max;
1394 ves_icall_System_Threading_Microsoft_ThreadPool_GetMinThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
1396 if (!worker_threads || !completion_port_threads)
1399 ensure_initialized (NULL);
1401 *worker_threads = threadpool->limit_worker_min;
1402 *completion_port_threads = threadpool->limit_io_min;
1406 ves_icall_System_Threading_Microsoft_ThreadPool_GetMaxThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
1408 if (!worker_threads || !completion_port_threads)
1411 ensure_initialized (NULL);
1413 *worker_threads = threadpool->limit_worker_max;
1414 *completion_port_threads = threadpool->limit_io_max;
1418 ves_icall_System_Threading_Microsoft_ThreadPool_SetMinThreadsNative (gint32 worker_threads, gint32 completion_port_threads)
1420 ensure_initialized (NULL);
1422 if (worker_threads <= 0 || worker_threads > threadpool->limit_worker_max)
1424 if (completion_port_threads <= 0 || completion_port_threads > threadpool->limit_io_max)
1427 threadpool->limit_worker_max = worker_threads;
1428 threadpool->limit_io_max = completion_port_threads;
1434 ves_icall_System_Threading_Microsoft_ThreadPool_SetMaxThreadsNative (gint32 worker_threads, gint32 completion_port_threads)
1436 gint cpu_count = mono_cpu_count ();
1438 ensure_initialized (NULL);
1440 if (worker_threads < threadpool->limit_worker_min || worker_threads < cpu_count)
1442 if (completion_port_threads < threadpool->limit_io_min || completion_port_threads < cpu_count)
1445 threadpool->limit_worker_max = worker_threads;
1446 threadpool->limit_io_max = completion_port_threads;
1452 ves_icall_System_Threading_Microsoft_ThreadPool_InitializeVMTp (MonoBoolean *enable_worker_tracking)
1454 ensure_initialized (enable_worker_tracking);
1458 ves_icall_System_Threading_Microsoft_ThreadPool_NotifyWorkItemComplete (void)
1460 ThreadPoolCounter counter;
1462 if (mono_domain_is_unloading (mono_domain_get ()) || mono_runtime_is_shutting_down ())
1465 heuristic_notify_work_completed ();
1467 if (heuristic_should_adjust ())
1468 heuristic_adjust ();
1470 counter.as_gint64 = COUNTER_READ ();
1471 return counter._.working <= counter._.max_working;
1475 ves_icall_System_Threading_Microsoft_ThreadPool_NotifyWorkItemProgressNative (void)
1477 heuristic_notify_work_completed ();
1479 if (heuristic_should_adjust ())
1480 heuristic_adjust ();
1484 ves_icall_System_Threading_Microsoft_ThreadPool_ReportThreadStatus (MonoBoolean is_working)
1487 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1491 ves_icall_System_Threading_Microsoft_ThreadPool_RequestWorkerThread (void)
1493 return worker_request (mono_domain_get ());
1496 MonoBoolean G_GNUC_UNUSED
1497 ves_icall_System_Threading_Microsoft_ThreadPool_PostQueuedCompletionStatus (MonoNativeOverlapped *native_overlapped)
1499 /* This copy the behavior of the current Mono implementation */
1500 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1504 MonoBoolean G_GNUC_UNUSED
1505 ves_icall_System_Threading_Microsoft_ThreadPool_BindIOCompletionCallbackNative (gpointer file_handle)
1507 /* This copy the behavior of the current Mono implementation */
1511 MonoBoolean G_GNUC_UNUSED
1512 ves_icall_System_Threading_Microsoft_ThreadPool_IsThreadPoolHosted (void)