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
27 #if !defined (HAVE_COMPLEX_H)
28 #include <../../support/libm/complex.h>
33 #include <mono/metadata/class-internals.h>
34 #include <mono/metadata/exception.h>
35 #include <mono/metadata/object.h>
36 #include <mono/metadata/object-internals.h>
37 #include <mono/metadata/threadpool-ms.h>
38 #include <mono/metadata/threadpool-ms-io.h>
39 #include <mono/metadata/threadpool-internals.h>
40 #include <mono/utils/atomic.h>
41 #include <mono/utils/mono-compiler.h>
42 #include <mono/utils/mono-proclib.h>
43 #include <mono/utils/mono-threads.h>
44 #include <mono/utils/mono-time.h>
45 #include <mono/utils/mono-rand.h>
47 #define CPU_USAGE_LOW 80
48 #define CPU_USAGE_HIGH 95
50 #define MONITOR_INTERVAL 100 // ms
52 /* The exponent to apply to the gain. 1.0 means to use linear gain,
53 * higher values will enhance large moves and damp small ones.
55 #define HILL_CLIMBING_GAIN_EXPONENT 2.0
57 /* The 'cost' of a thread. 0 means drive for increased throughput regardless
58 * of thread count, higher values bias more against higher thread counts.
60 #define HILL_CLIMBING_BIAS 0.15
62 #define HILL_CLIMBING_WAVE_PERIOD 4
63 #define HILL_CLIMBING_MAX_WAVE_MAGNITUDE 20
64 #define HILL_CLIMBING_WAVE_MAGNITUDE_MULTIPLIER 1.0
65 #define HILL_CLIMBING_WAVE_HISTORY_SIZE 8
66 #define HILL_CLIMBING_TARGET_SIGNAL_TO_NOISE_RATIO 3.0
67 #define HILL_CLIMBING_MAX_CHANGE_PER_SECOND 4
68 #define HILL_CLIMBING_MAX_CHANGE_PER_SAMPLE 20
69 #define HILL_CLIMBING_SAMPLE_INTERVAL_LOW 10
70 #define HILL_CLIMBING_SAMPLE_INTERVAL_HIGH 200
71 #define HILL_CLIMBING_ERROR_SMOOTHING_FACTOR 0.01
72 #define HILL_CLIMBING_MAX_SAMPLE_ERROR_PERCENT 0.15
74 /* Keep in sync with System.Threading.RuntimeWorkItem */
75 struct _MonoRuntimeWorkItem {
77 MonoAsyncResult *async_result;
82 gint16 max_working; /* determined by heuristic */
83 gint16 active; /* working or waiting on thread_work_sem; warm threads */
92 gint32 outstanding_request;
97 gint32 samples_to_measure;
98 gdouble target_throughput_ratio;
99 gdouble target_signal_to_noise_ratio;
100 gdouble max_change_per_second;
101 gdouble max_change_per_sample;
102 gint32 max_thread_wave_magnitude;
103 gint32 sample_interval_low;
104 gdouble thread_magnitude_multiplier;
105 gint32 sample_interval_high;
106 gdouble throughput_error_smoothing_factor;
107 gdouble gain_exponent;
108 gdouble max_sample_error;
110 gdouble current_control_setting;
111 gint64 total_samples;
112 gint16 last_thread_count;
113 gdouble elapsed_since_last_change;
114 gdouble completions_since_last_change;
116 gdouble average_throughput_noise;
119 gdouble *thread_counts;
121 guint32 current_sample_interval;
122 gpointer random_interval_generator;
124 gint32 accumulated_completion_count;
125 gdouble accumulated_sample_duration;
126 } ThreadPoolHillClimbing;
129 ThreadPoolCounter counters;
131 GPtrArray *domains; // ThreadPoolDomain* []
132 mono_mutex_t domains_lock;
134 GPtrArray *working_threads; // MonoInternalThread* []
135 mono_mutex_t working_threads_lock;
137 GPtrArray *parked_threads; // mono_cond_t* []
138 mono_mutex_t parked_threads_lock;
140 gint32 heuristic_completions;
141 guint32 heuristic_sample_start;
142 guint32 heuristic_last_dequeue; // ms
143 guint32 heuristic_last_adjustment; // ms
144 guint32 heuristic_adjustment_interval; // ms
145 ThreadPoolHillClimbing heuristic_hill_climbing;
146 mono_mutex_t heuristic_lock;
148 gint32 limit_worker_min;
149 gint32 limit_worker_max;
153 MonoCpuUsageState *cpu_usage_state;
156 /* suspended by the debugger */
162 TRANSITION_INITIALIZING,
163 TRANSITION_RANDOM_MOVE,
164 TRANSITION_CLIMBING_MOVE,
165 TRANSITION_CHANGE_POINT,
166 TRANSITION_STABILIZING,
167 TRANSITION_STARVATION,
168 TRANSITION_THREAD_TIMED_OUT,
169 TRANSITION_UNDEFINED,
170 } ThreadPoolHeuristicStateTransition;
173 MONITOR_STATUS_REQUESTED,
174 MONITOR_STATUS_WAITING_FOR_REQUEST,
175 MONITOR_STATUS_NOT_RUNNING,
178 static gint32 status = STATUS_NOT_INITIALIZED;
179 static gint32 monitor_status = MONITOR_STATUS_NOT_RUNNING;
181 static ThreadPool* threadpool;
183 #define COUNTER_CHECK(counter) \
185 g_assert (counter._.max_working > 0); \
186 g_assert (counter._.active >= 0); \
189 #define COUNTER_READ() ((ThreadPoolCounter) InterlockedRead64 (&threadpool->counters.as_gint64))
191 #define COUNTER_ATOMIC(var,block) \
193 ThreadPoolCounter __old; \
195 g_assert (threadpool); \
196 (var) = __old = COUNTER_READ (); \
198 COUNTER_CHECK (var); \
199 } while (InterlockedCompareExchange64 (&threadpool->counters.as_gint64, (var).as_gint64, __old.as_gint64) != __old.as_gint64); \
202 #define COUNTER_TRY_ATOMIC(res,var,block) \
204 ThreadPoolCounter __old; \
206 g_assert (threadpool); \
207 (var) = __old = COUNTER_READ (); \
210 COUNTER_CHECK (var); \
211 (res) = InterlockedCompareExchange64 (&threadpool->counters.as_gint64, (var).as_gint64, __old.as_gint64) == __old.as_gint64; \
219 return mono_rand_init (NULL, 0);
223 rand_next (gpointer *handle, guint32 min, guint32 max)
226 if (!mono_rand_try_get_uint32 (handle, &val, min, max)) {
227 // FIXME handle error
228 g_assert_not_reached ();
234 rand_free (gpointer handle)
236 mono_rand_close (handle);
240 ensure_initialized (gboolean *enable_worker_tracking)
242 ThreadPoolHillClimbing *hc;
243 const char *threads_per_cpu_env;
244 gint threads_per_cpu;
247 if (enable_worker_tracking) {
248 // TODO implement some kind of switch to have the possibily to use it
249 *enable_worker_tracking = FALSE;
252 if (status >= STATUS_INITIALIZED)
254 if (status == STATUS_INITIALIZING || InterlockedCompareExchange (&status, STATUS_INITIALIZING, STATUS_NOT_INITIALIZED) != STATUS_NOT_INITIALIZED) {
255 while (status == STATUS_INITIALIZING)
256 mono_thread_info_yield ();
257 g_assert (status >= STATUS_INITIALIZED);
261 g_assert (!threadpool);
262 threadpool = g_new0 (ThreadPool, 1);
263 g_assert (threadpool);
265 threadpool->domains = g_ptr_array_new ();
266 mono_mutex_init_recursive (&threadpool->domains_lock);
268 threadpool->parked_threads = g_ptr_array_new ();
269 mono_mutex_init (&threadpool->parked_threads_lock);
271 threadpool->working_threads = g_ptr_array_new ();
272 mono_mutex_init (&threadpool->working_threads_lock);
274 threadpool->heuristic_adjustment_interval = 10;
275 mono_mutex_init (&threadpool->heuristic_lock);
279 hc = &threadpool->heuristic_hill_climbing;
281 hc->wave_period = HILL_CLIMBING_WAVE_PERIOD;
282 hc->max_thread_wave_magnitude = HILL_CLIMBING_MAX_WAVE_MAGNITUDE;
283 hc->thread_magnitude_multiplier = (gdouble) HILL_CLIMBING_WAVE_MAGNITUDE_MULTIPLIER;
284 hc->samples_to_measure = hc->wave_period * HILL_CLIMBING_WAVE_HISTORY_SIZE;
285 hc->target_throughput_ratio = (gdouble) HILL_CLIMBING_BIAS;
286 hc->target_signal_to_noise_ratio = (gdouble) HILL_CLIMBING_TARGET_SIGNAL_TO_NOISE_RATIO;
287 hc->max_change_per_second = (gdouble) HILL_CLIMBING_MAX_CHANGE_PER_SECOND;
288 hc->max_change_per_sample = (gdouble) HILL_CLIMBING_MAX_CHANGE_PER_SAMPLE;
289 hc->sample_interval_low = HILL_CLIMBING_SAMPLE_INTERVAL_LOW;
290 hc->sample_interval_high = HILL_CLIMBING_SAMPLE_INTERVAL_HIGH;
291 hc->throughput_error_smoothing_factor = (gdouble) HILL_CLIMBING_ERROR_SMOOTHING_FACTOR;
292 hc->gain_exponent = (gdouble) HILL_CLIMBING_GAIN_EXPONENT;
293 hc->max_sample_error = (gdouble) HILL_CLIMBING_MAX_SAMPLE_ERROR_PERCENT;
294 hc->current_control_setting = 0;
295 hc->total_samples = 0;
296 hc->last_thread_count = 0;
297 hc->average_throughput_noise = 0;
298 hc->elapsed_since_last_change = 0;
299 hc->accumulated_completion_count = 0;
300 hc->accumulated_sample_duration = 0;
301 hc->samples = g_new0 (gdouble, hc->samples_to_measure);
302 hc->thread_counts = g_new0 (gdouble, hc->samples_to_measure);
303 hc->random_interval_generator = rand_create ();
304 hc->current_sample_interval = rand_next (&hc->random_interval_generator, hc->sample_interval_low, hc->sample_interval_high);
306 if (!(threads_per_cpu_env = g_getenv ("MONO_THREADS_PER_CPU")))
309 threads_per_cpu = CLAMP (atoi (threads_per_cpu_env), 1, 50);
311 threads_count = mono_cpu_count () * threads_per_cpu;
313 threadpool->limit_worker_min = threadpool->limit_io_min = threads_count;
314 threadpool->limit_worker_max = threadpool->limit_io_max = threads_count * 100;
316 threadpool->counters._.max_working = threadpool->limit_worker_min;
318 threadpool->cpu_usage_state = g_new0 (MonoCpuUsageState, 1);
320 threadpool->suspended = FALSE;
322 status = STATUS_INITIALIZED;
326 ensure_cleanedup (void)
328 if (status == STATUS_NOT_INITIALIZED && InterlockedCompareExchange (&status, STATUS_CLEANED_UP, STATUS_NOT_INITIALIZED) == STATUS_NOT_INITIALIZED)
330 if (status == STATUS_INITIALIZING) {
331 while (status == STATUS_INITIALIZING)
332 mono_thread_info_yield ();
334 if (status == STATUS_CLEANED_UP)
336 if (status == STATUS_CLEANING_UP || InterlockedCompareExchange (&status, STATUS_CLEANING_UP, STATUS_INITIALIZED) != STATUS_INITIALIZED) {
337 while (status == STATUS_CLEANING_UP)
338 mono_thread_info_yield ();
339 g_assert (status == STATUS_CLEANED_UP);
343 /* we make the assumption along the code that we are
344 * cleaning up only if the runtime is shutting down */
345 g_assert (mono_runtime_is_shutting_down ());
347 /* Unpark all worker threads */
348 mono_mutex_lock (&threadpool->parked_threads_lock);
351 ThreadPoolCounter counter = COUNTER_READ ();
352 if (counter._.active == 0 && counter._.parked == 0)
354 if (counter._.active == 1) {
355 MonoInternalThread *thread = mono_thread_internal_current ();
356 if (thread->threadpool_thread) {
357 /* if there is only one active thread
358 * left and it's the current one */
362 for (i = 0; i < threadpool->parked_threads->len; ++i) {
363 mono_cond_t *cond = (mono_cond_t*) g_ptr_array_index (threadpool->parked_threads, i);
364 mono_cond_signal (cond);
366 mono_mutex_unlock (&threadpool->parked_threads_lock);
368 mono_mutex_lock (&threadpool->parked_threads_lock);
370 mono_mutex_unlock (&threadpool->parked_threads_lock);
372 while (monitor_status != MONITOR_STATUS_NOT_RUNNING)
375 g_ptr_array_free (threadpool->domains, TRUE);
376 mono_mutex_destroy (&threadpool->domains_lock);
378 g_ptr_array_free (threadpool->parked_threads, TRUE);
379 mono_mutex_destroy (&threadpool->parked_threads_lock);
381 g_ptr_array_free (threadpool->working_threads, TRUE);
382 mono_mutex_destroy (&threadpool->working_threads_lock);
384 mono_mutex_destroy (&threadpool->heuristic_lock);
385 g_free (threadpool->heuristic_hill_climbing.samples);
386 g_free (threadpool->heuristic_hill_climbing.thread_counts);
387 rand_free (threadpool->heuristic_hill_climbing.random_interval_generator);
389 g_free (threadpool->cpu_usage_state);
391 g_assert (threadpool);
394 g_assert (!threadpool);
396 status = STATUS_CLEANED_UP;
400 mono_threadpool_ms_enqueue_work_item (MonoDomain *domain, MonoObject *work_item)
402 static MonoClass *threadpool_class = NULL;
403 static MonoMethod *unsafe_queue_custom_work_item_method = NULL;
404 MonoDomain *current_domain;
408 g_assert (work_item);
410 if (!threadpool_class)
411 threadpool_class = mono_class_from_name (mono_defaults.corlib, "System.Threading", "ThreadPool");
412 g_assert (threadpool_class);
414 if (!unsafe_queue_custom_work_item_method)
415 unsafe_queue_custom_work_item_method = mono_class_get_method_from_name (threadpool_class, "UnsafeQueueCustomWorkItem", 2);
416 g_assert (unsafe_queue_custom_work_item_method);
420 args [0] = (gpointer) work_item;
421 args [1] = (gpointer) mono_value_box (domain, mono_defaults.boolean_class, &f);
423 current_domain = mono_domain_get ();
424 if (current_domain == domain) {
425 mono_runtime_invoke (unsafe_queue_custom_work_item_method, NULL, args, NULL);
427 mono_thread_push_appdomain_ref (domain);
428 if (mono_domain_set (domain, FALSE)) {
429 mono_runtime_invoke (unsafe_queue_custom_work_item_method, NULL, args, NULL);
430 mono_domain_set (current_domain, TRUE);
432 mono_thread_pop_appdomain_ref ();
437 mono_threadpool_ms_enqueue_async_result (MonoDomain *domain, MonoAsyncResult *ares)
439 static MonoClass *runtime_work_item_class = NULL;
440 MonoRuntimeWorkItem *rwi;
444 if (!runtime_work_item_class)
445 runtime_work_item_class = mono_class_from_name (mono_defaults.corlib, "System.Threading", "MonoRuntimeWorkItem");
446 g_assert (runtime_work_item_class);
448 rwi = (MonoRuntimeWorkItem*) mono_object_new (domain, runtime_work_item_class);
449 MONO_OBJECT_SETREF (rwi, async_result, ares);
451 mono_threadpool_ms_enqueue_work_item (domain, (MonoObject*) rwi);
455 domain_add (ThreadPoolDomain *tpdomain)
461 mono_mutex_lock (&threadpool->domains_lock);
462 len = threadpool->domains->len;
463 for (i = 0; i < len; ++i) {
464 if (g_ptr_array_index (threadpool->domains, i) == tpdomain)
468 g_ptr_array_add (threadpool->domains, tpdomain);
469 mono_mutex_unlock (&threadpool->domains_lock);
473 domain_remove (ThreadPoolDomain *tpdomain)
479 mono_mutex_lock (&threadpool->domains_lock);
480 res = g_ptr_array_remove (threadpool->domains, tpdomain);
481 mono_mutex_unlock (&threadpool->domains_lock);
486 static ThreadPoolDomain *
487 domain_get_or_create (MonoDomain *domain)
489 ThreadPoolDomain *tpdomain = NULL;
494 mono_mutex_lock (&threadpool->domains_lock);
495 for (i = 0; i < threadpool->domains->len; ++i) {
496 ThreadPoolDomain *tmp = g_ptr_array_index (threadpool->domains, i);
497 if (tmp->domain == domain) {
503 tpdomain = g_new0 (ThreadPoolDomain, 1);
504 tpdomain->domain = domain;
505 domain_add (tpdomain);
507 mono_mutex_unlock (&threadpool->domains_lock);
512 domain_any_has_request ()
514 gboolean res = FALSE;
517 mono_mutex_lock (&threadpool->domains_lock);
518 for (i = 0; i < threadpool->domains->len; ++i) {
519 ThreadPoolDomain *tmp = g_ptr_array_index (threadpool->domains, i);
520 if (tmp->outstanding_request > 0) {
525 mono_mutex_unlock (&threadpool->domains_lock);
529 static ThreadPoolDomain *
530 domain_get_next (ThreadPoolDomain *current)
532 ThreadPoolDomain *tpdomain = NULL;
535 mono_mutex_lock (&threadpool->domains_lock);
536 len = threadpool->domains->len;
538 guint i, current_idx = -1;
540 for (i = 0; i < len; ++i) {
541 if (current == g_ptr_array_index (threadpool->domains, i)) {
546 g_assert (current_idx >= 0);
548 for (i = current_idx + 1; i < len + current_idx + 1; ++i) {
549 ThreadPoolDomain *tmp = g_ptr_array_index (threadpool->domains, i % len);
550 if (tmp->outstanding_request > 0) {
552 tpdomain->outstanding_request --;
553 g_assert (tpdomain->outstanding_request >= 0);
558 mono_mutex_unlock (&threadpool->domains_lock);
566 mono_cond_init (&cond, NULL);
568 mono_mutex_lock (&threadpool->parked_threads_lock);
569 g_ptr_array_add (threadpool->parked_threads, &cond);
570 mono_cond_wait (&cond, &threadpool->parked_threads_lock);
571 g_ptr_array_remove (threadpool->parked_threads, &cond);
572 mono_mutex_unlock (&threadpool->parked_threads_lock);
574 mono_cond_destroy (&cond);
578 worker_try_unpark (void)
580 gboolean res = FALSE;
583 mono_mutex_lock (&threadpool->parked_threads_lock);
584 len = threadpool->parked_threads->len;
586 mono_cond_t *cond = (mono_cond_t*) g_ptr_array_index (threadpool->parked_threads, len - 1);
587 mono_cond_signal (cond);
590 mono_mutex_unlock (&threadpool->parked_threads_lock);
595 worker_thread (gpointer data)
597 static MonoClass *threadpool_wait_callback_class = NULL;
598 static MonoMethod *perform_wait_callback_method = NULL;
599 MonoInternalThread *thread;
600 ThreadPoolDomain *tpdomain;
601 ThreadPoolCounter counter;
602 gboolean retire = FALSE;
604 g_assert (status >= STATUS_INITIALIZED);
608 g_assert (tpdomain->domain);
610 if (mono_runtime_is_shutting_down () || mono_domain_is_unloading (tpdomain->domain)) {
611 COUNTER_ATOMIC (counter, { counter._.active --; });
615 if (!threadpool_wait_callback_class)
616 threadpool_wait_callback_class = mono_class_from_name (mono_defaults.corlib, "System.Threading.Microsoft", "_ThreadPoolWaitCallback");
617 g_assert (threadpool_wait_callback_class);
619 if (!perform_wait_callback_method)
620 perform_wait_callback_method = mono_class_get_method_from_name (threadpool_wait_callback_class, "PerformWaitCallback", 0);
621 g_assert (perform_wait_callback_method);
623 g_assert (threadpool);
625 thread = mono_thread_internal_current ();
628 mono_mutex_lock (&threadpool->domains_lock);
634 g_assert (tpdomain->domain);
636 tpdomain->domain->threadpool_jobs ++;
638 mono_mutex_unlock (&threadpool->domains_lock);
640 mono_mutex_lock (&threadpool->working_threads_lock);
641 g_ptr_array_add (threadpool->working_threads, thread);
642 mono_mutex_unlock (&threadpool->working_threads_lock);
644 COUNTER_ATOMIC (counter, { counter._.working ++; });
646 mono_thread_push_appdomain_ref (tpdomain->domain);
647 if (mono_domain_set (tpdomain->domain, FALSE)) {
648 MonoObject *exc = NULL;
649 MonoObject *res = mono_runtime_invoke (perform_wait_callback_method, NULL, NULL, &exc);
651 mono_internal_thread_unhandled_exception (exc);
652 else if (res && *(MonoBoolean*) mono_object_unbox (res) == FALSE)
655 mono_thread_clr_state (thread , ~ThreadState_Background);
656 if (!mono_thread_test_state (thread , ThreadState_Background))
657 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
659 mono_thread_pop_appdomain_ref ();
661 COUNTER_ATOMIC (counter, { counter._.working --; });
663 mono_mutex_lock (&threadpool->working_threads_lock);
664 g_ptr_array_remove_fast (threadpool->working_threads, thread);
665 mono_mutex_unlock (&threadpool->working_threads_lock);
667 mono_mutex_lock (&threadpool->domains_lock);
669 tpdomain->domain->threadpool_jobs --;
670 g_assert (tpdomain->domain->threadpool_jobs >= 0);
672 if (tpdomain->domain->threadpool_jobs == 0 && mono_domain_is_unloading (tpdomain->domain)) {
673 gboolean removed = domain_remove (tpdomain);
675 if (tpdomain->domain->cleanup_semaphore)
676 ReleaseSemaphore (tpdomain->domain->cleanup_semaphore, 1, NULL);
681 for (i = 0, c = 5; i < c; ++i) {
682 if (mono_runtime_is_shutting_down ())
686 tpdomain = domain_get_next (tpdomain);
692 gboolean park = TRUE;
694 COUNTER_ATOMIC (counter, {
695 if (counter._.active <= counter._.max_working) {
704 mono_mutex_unlock (&threadpool->domains_lock);
706 mono_mutex_lock (&threadpool->domains_lock);
708 COUNTER_ATOMIC (counter, {
717 } while (tpdomain && !mono_runtime_is_shutting_down ());
719 mono_mutex_unlock (&threadpool->domains_lock);
721 COUNTER_ATOMIC (counter, { counter._.active --; });
725 worker_try_create (ThreadPoolDomain *tpdomain)
728 g_assert (tpdomain->domain);
730 return mono_thread_create_internal (tpdomain->domain, worker_thread, tpdomain, TRUE, 0) != NULL;
733 static void monitor_ensure_running (void);
736 worker_request (MonoDomain *domain)
738 ThreadPoolDomain *tpdomain;
739 ThreadPoolCounter counter;
742 g_assert (threadpool);
744 if (mono_runtime_is_shutting_down () || mono_domain_is_unloading (domain))
747 mono_mutex_lock (&threadpool->domains_lock);
748 tpdomain = domain_get_or_create (domain);
750 tpdomain->outstanding_request ++;
751 mono_mutex_unlock (&threadpool->domains_lock);
753 if (threadpool->suspended)
756 monitor_ensure_running ();
758 if (worker_try_unpark ())
761 COUNTER_ATOMIC (counter, {
762 if (counter._.active >= counter._.max_working)
767 if (worker_try_create (tpdomain))
770 COUNTER_ATOMIC (counter, { counter._.active --; });
775 monitor_should_keep_running (void)
777 g_assert (monitor_status == MONITOR_STATUS_WAITING_FOR_REQUEST || monitor_status == MONITOR_STATUS_REQUESTED);
779 if (InterlockedExchange (&monitor_status, MONITOR_STATUS_WAITING_FOR_REQUEST) == MONITOR_STATUS_WAITING_FOR_REQUEST) {
780 if (mono_runtime_is_shutting_down () || !domain_any_has_request ()) {
781 if (InterlockedExchange (&monitor_status, MONITOR_STATUS_NOT_RUNNING) == MONITOR_STATUS_WAITING_FOR_REQUEST)
786 g_assert (monitor_status == MONITOR_STATUS_WAITING_FOR_REQUEST || monitor_status == MONITOR_STATUS_REQUESTED);
792 monitor_sufficient_delay_since_last_dequeue (void)
796 g_assert (threadpool);
798 if (threadpool->cpu_usage < CPU_USAGE_LOW) {
799 threshold = MONITOR_INTERVAL;
801 ThreadPoolCounter counter = COUNTER_READ ();
802 threshold = counter._.max_working * MONITOR_INTERVAL * 2;
805 return mono_msec_ticks () >= threadpool->heuristic_last_dequeue + threshold;
808 static void hill_climbing_force_change (gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition);
811 monitor_thread (void)
813 MonoInternalThread *current_thread = mono_thread_internal_current ();
816 mono_cpu_usage (threadpool->cpu_usage_state);
819 MonoInternalThread *thread;
820 gboolean all_waitsleepjoin = TRUE;
821 gint32 interval_left = MONITOR_INTERVAL;
822 gint32 awake = 0; /* number of spurious awakes we tolerate before doing a round of rebalancing */
824 g_assert (monitor_status != MONITOR_STATUS_NOT_RUNNING);
829 if (mono_runtime_is_shutting_down ())
832 ts = mono_msec_ticks ();
833 if (SleepEx (interval_left, TRUE) == 0)
835 interval_left -= mono_msec_ticks () - ts;
837 if ((current_thread->state & (ThreadState_StopRequested | ThreadState_SuspendRequested)) != 0)
838 mono_thread_interruption_checkpoint ();
839 } while (interval_left > 0 && ++awake < 10);
841 if (threadpool->suspended)
844 if (mono_runtime_is_shutting_down () || !domain_any_has_request ())
847 mono_mutex_lock (&threadpool->working_threads_lock);
848 for (i = 0; i < threadpool->working_threads->len; ++i) {
849 thread = g_ptr_array_index (threadpool->working_threads, i);
850 if ((thread->state & ThreadState_WaitSleepJoin) == 0) {
851 all_waitsleepjoin = FALSE;
855 mono_mutex_unlock (&threadpool->working_threads_lock);
857 if (all_waitsleepjoin) {
858 ThreadPoolCounter counter;
859 COUNTER_ATOMIC (counter, { counter._.max_working ++; });
860 hill_climbing_force_change (counter._.max_working, TRANSITION_STARVATION);
863 threadpool->cpu_usage = mono_cpu_usage (threadpool->cpu_usage_state);
865 if (monitor_sufficient_delay_since_last_dequeue ()) {
866 for (i = 0; i < 5; ++i) {
867 ThreadPoolDomain *tpdomain;
868 ThreadPoolCounter counter;
871 if (mono_runtime_is_shutting_down ())
874 if (worker_try_unpark ())
877 COUNTER_TRY_ATOMIC (success, counter, {
878 if (counter._.active >= counter._.max_working)
886 tpdomain = domain_get_next (NULL);
887 if (tpdomain && worker_try_create (tpdomain))
890 COUNTER_ATOMIC (counter, { counter._.active --; });
893 } while (monitor_should_keep_running ());
897 monitor_ensure_running (void)
900 switch (monitor_status) {
901 case MONITOR_STATUS_REQUESTED:
903 case MONITOR_STATUS_WAITING_FOR_REQUEST:
904 InterlockedCompareExchange (&monitor_status, MONITOR_STATUS_REQUESTED, MONITOR_STATUS_WAITING_FOR_REQUEST);
906 case MONITOR_STATUS_NOT_RUNNING:
907 if (InterlockedCompareExchange (&monitor_status, MONITOR_STATUS_REQUESTED, MONITOR_STATUS_NOT_RUNNING) == MONITOR_STATUS_NOT_RUNNING) {
908 if (!mono_thread_create_internal (mono_get_root_domain (), monitor_thread, NULL, TRUE, SMALL_STACK))
909 monitor_status = MONITOR_STATUS_NOT_RUNNING;
913 default: g_assert_not_reached ();
919 hill_climbing_change_thread_count (gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition)
921 ThreadPoolHillClimbing *hc;
923 g_assert (threadpool);
925 hc = &threadpool->heuristic_hill_climbing;
927 hc->last_thread_count = new_thread_count;
928 hc->current_sample_interval = rand_next (&hc->random_interval_generator, hc->sample_interval_low, hc->sample_interval_high);
929 hc->elapsed_since_last_change = 0;
930 hc->completions_since_last_change = 0;
934 hill_climbing_force_change (gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition)
936 ThreadPoolHillClimbing *hc;
938 g_assert (threadpool);
940 hc = &threadpool->heuristic_hill_climbing;
942 if (new_thread_count != hc->last_thread_count) {
943 hc->current_control_setting += new_thread_count - hc->last_thread_count;
944 hill_climbing_change_thread_count (new_thread_count, transition);
948 static double complex
949 hill_climbing_get_wave_component (gdouble *samples, guint sample_count, gdouble period)
951 ThreadPoolHillClimbing *hc;
952 gdouble w, cosine, sine, coeff, q0, q1, q2;
955 g_assert (threadpool);
956 g_assert (sample_count >= period);
957 g_assert (period >= 2);
959 hc = &threadpool->heuristic_hill_climbing;
961 w = 2.0 * M_PI / period;
964 coeff = 2.0 * cosine;
967 for (i = 0; i < sample_count; ++i) {
968 q0 = coeff * q1 - q2 + samples [(hc->total_samples - sample_count + i) % hc->samples_to_measure];
973 return ((q1 - q2 * cosine) + (q2 * sine) * I) / ((gdouble) sample_count);
977 hill_climbing_update (gint16 current_thread_count, guint32 sample_duration, gint32 completions, guint32 *adjustment_interval)
979 ThreadPoolHillClimbing *hc;
980 ThreadPoolHeuristicStateTransition transition;
982 gdouble throughput_error_estimate;
988 gint new_thread_wave_magnitude;
989 gint new_thread_count;
990 double complex thread_wave_component;
991 double complex throughput_wave_component;
992 double complex ratio;
994 g_assert (threadpool);
995 g_assert (adjustment_interval);
997 hc = &threadpool->heuristic_hill_climbing;
999 /* If someone changed the thread count without telling us, update our records accordingly. */
1000 if (current_thread_count != hc->last_thread_count)
1001 hill_climbing_force_change (current_thread_count, TRANSITION_INITIALIZING);
1003 /* Update the cumulative stats for this thread count */
1004 hc->elapsed_since_last_change += sample_duration;
1005 hc->completions_since_last_change += completions;
1007 /* Add in any data we've already collected about this sample */
1008 sample_duration += hc->accumulated_sample_duration;
1009 completions += hc->accumulated_completion_count;
1011 /* We need to make sure we're collecting reasonably accurate data. Since we're just counting the end
1012 * of each work item, we are goinng to be missing some data about what really happened during the
1013 * sample interval. The count produced by each thread includes an initial work item that may have
1014 * started well before the start of the interval, and each thread may have been running some new
1015 * work item for some time before the end of the interval, which did not yet get counted. So
1016 * our count is going to be off by +/- threadCount workitems.
1018 * The exception is that the thread that reported to us last time definitely wasn't running any work
1019 * at that time, and the thread that's reporting now definitely isn't running a work item now. So
1020 * we really only need to consider threadCount-1 threads.
1022 * Thus the percent error in our count is +/- (threadCount-1)/numCompletions.
1024 * We cannot rely on the frequency-domain analysis we'll be doing later to filter out this error, because
1025 * of the way it accumulates over time. If this sample is off by, say, 33% in the negative direction,
1026 * then the next one likely will be too. The one after that will include the sum of the completions
1027 * we missed in the previous samples, and so will be 33% positive. So every three samples we'll have
1028 * two "low" samples and one "high" sample. This will appear as periodic variation right in the frequency
1029 * range we're targeting, which will not be filtered by the frequency-domain translation. */
1030 if (hc->total_samples > 0 && ((current_thread_count - 1.0) / completions) >= hc->max_sample_error) {
1031 /* Not accurate enough yet. Let's accumulate the data so
1032 * far, and tell the ThreadPool to collect a little more. */
1033 hc->accumulated_sample_duration = sample_duration;
1034 hc->accumulated_completion_count = completions;
1035 *adjustment_interval = 10;
1036 return current_thread_count;
1039 /* We've got enouugh data for our sample; reset our accumulators for next time. */
1040 hc->accumulated_sample_duration = 0;
1041 hc->accumulated_completion_count = 0;
1043 /* Add the current thread count and throughput sample to our history. */
1044 throughput = ((gdouble) completions) / sample_duration;
1046 sample_index = hc->total_samples % hc->samples_to_measure;
1047 hc->samples [sample_index] = throughput;
1048 hc->thread_counts [sample_index] = current_thread_count;
1049 hc->total_samples ++;
1051 /* Set up defaults for our metrics. */
1052 thread_wave_component = 0;
1053 throughput_wave_component = 0;
1054 throughput_error_estimate = 0;
1058 transition = TRANSITION_WARMUP;
1060 /* How many samples will we use? It must be at least the three wave periods we're looking for, and it must also
1061 * be a whole multiple of the primary wave's period; otherwise the frequency we're looking for will fall between
1062 * two frequency bands in the Fourier analysis, and we won't be able to measure it accurately. */
1063 sample_count = ((gint) MIN (hc->total_samples - 1, hc->samples_to_measure) / hc->wave_period) * hc->wave_period;
1065 if (sample_count > hc->wave_period) {
1067 gdouble average_throughput;
1068 gdouble average_thread_count;
1069 gdouble sample_sum = 0;
1070 gdouble thread_sum = 0;
1072 /* Average the throughput and thread count samples, so we can scale the wave magnitudes later. */
1073 for (i = 0; i < sample_count; ++i) {
1074 guint j = (hc->total_samples - sample_count + i) % hc->samples_to_measure;
1075 sample_sum += hc->samples [j];
1076 thread_sum += hc->thread_counts [j];
1079 average_throughput = sample_sum / sample_count;
1080 average_thread_count = thread_sum / sample_count;
1082 if (average_throughput > 0 && average_thread_count > 0) {
1083 gdouble noise_for_confidence, adjacent_period_1, adjacent_period_2;
1085 /* Calculate the periods of the adjacent frequency bands we'll be using to
1086 * measure noise levels. We want the two adjacent Fourier frequency bands. */
1087 adjacent_period_1 = sample_count / (((gdouble) sample_count) / ((gdouble) hc->wave_period) + 1);
1088 adjacent_period_2 = sample_count / (((gdouble) sample_count) / ((gdouble) hc->wave_period) - 1);
1090 /* Get the the three different frequency components of the throughput (scaled by average
1091 * throughput). Our "error" estimate (the amount of noise that might be present in the
1092 * frequency band we're really interested in) is the average of the adjacent bands. */
1093 throughput_wave_component = hill_climbing_get_wave_component (hc->samples, sample_count, hc->wave_period) / average_throughput;
1094 throughput_error_estimate = cabs (hill_climbing_get_wave_component (hc->samples, sample_count, adjacent_period_1) / average_throughput);
1096 if (adjacent_period_2 <= sample_count) {
1097 throughput_error_estimate = MAX (throughput_error_estimate, cabs (hill_climbing_get_wave_component (
1098 hc->samples, sample_count, adjacent_period_2) / average_throughput));
1101 /* Do the same for the thread counts, so we have something to compare to. We don't
1102 * measure thread count noise, because there is none; these are exact measurements. */
1103 thread_wave_component = hill_climbing_get_wave_component (hc->thread_counts, sample_count, hc->wave_period) / average_thread_count;
1105 /* Update our moving average of the throughput noise. We'll use this
1106 * later as feedback to determine the new size of the thread wave. */
1107 if (hc->average_throughput_noise == 0) {
1108 hc->average_throughput_noise = throughput_error_estimate;
1110 hc->average_throughput_noise = (hc->throughput_error_smoothing_factor * throughput_error_estimate)
1111 + ((1.0 + hc->throughput_error_smoothing_factor) * hc->average_throughput_noise);
1114 if (cabs (thread_wave_component) > 0) {
1115 /* Adjust the throughput wave so it's centered around the target wave,
1116 * and then calculate the adjusted throughput/thread ratio. */
1117 ratio = (throughput_wave_component - (hc->target_throughput_ratio * thread_wave_component)) / thread_wave_component;
1118 transition = TRANSITION_CLIMBING_MOVE;
1121 transition = TRANSITION_STABILIZING;
1124 noise_for_confidence = MAX (hc->average_throughput_noise, throughput_error_estimate);
1125 if (noise_for_confidence > 0) {
1126 confidence = cabs (thread_wave_component) / noise_for_confidence / hc->target_signal_to_noise_ratio;
1128 /* there is no noise! */
1134 /* We use just the real part of the complex ratio we just calculated. If the throughput signal
1135 * is exactly in phase with the thread signal, this will be the same as taking the magnitude of
1136 * the complex move and moving that far up. If they're 180 degrees out of phase, we'll move
1137 * backward (because this indicates that our changes are having the opposite of the intended effect).
1138 * If they're 90 degrees out of phase, we won't move at all, because we can't tell wether we're
1139 * having a negative or positive effect on throughput. */
1140 move = creal (ratio);
1141 move = CLAMP (move, -1.0, 1.0);
1143 /* Apply our confidence multiplier. */
1144 move *= CLAMP (confidence, -1.0, 1.0);
1146 /* Now apply non-linear gain, such that values around zero are attenuated, while higher values
1147 * are enhanced. This allows us to move quickly if we're far away from the target, but more slowly
1148 * if we're getting close, giving us rapid ramp-up without wild oscillations around the target. */
1149 gain = hc->max_change_per_second * sample_duration;
1150 move = pow (fabs (move), hc->gain_exponent) * (move >= 0.0 ? 1 : -1) * gain;
1151 move = MIN (move, hc->max_change_per_sample);
1153 /* If the result was positive, and CPU is > 95%, refuse the move. */
1154 if (move > 0.0 && threadpool->cpu_usage > CPU_USAGE_HIGH)
1157 /* Apply the move to our control setting. */
1158 hc->current_control_setting += move;
1160 /* Calculate the new thread wave magnitude, which is based on the moving average we've been keeping of the
1161 * throughput error. This average starts at zero, so we'll start with a nice safe little wave at first. */
1162 new_thread_wave_magnitude = (gint)(0.5 + (hc->current_control_setting * hc->average_throughput_noise
1163 * hc->target_signal_to_noise_ratio * hc->thread_magnitude_multiplier * 2.0));
1164 new_thread_wave_magnitude = CLAMP (new_thread_wave_magnitude, 1, hc->max_thread_wave_magnitude);
1166 /* Make sure our control setting is within the ThreadPool's limits. */
1167 hc->current_control_setting = CLAMP (hc->current_control_setting, threadpool->limit_worker_min, threadpool->limit_worker_max - new_thread_wave_magnitude);
1169 /* Calculate the new thread count (control setting + square wave). */
1170 new_thread_count = (gint)(hc->current_control_setting + new_thread_wave_magnitude * ((hc->total_samples / (hc->wave_period / 2)) % 2));
1172 /* Make sure the new thread count doesn't exceed the ThreadPool's limits. */
1173 new_thread_count = CLAMP (new_thread_count, threadpool->limit_worker_min, threadpool->limit_worker_max);
1175 if (new_thread_count != current_thread_count)
1176 hill_climbing_change_thread_count (new_thread_count, transition);
1178 if (creal (ratio) < 0.0 && new_thread_count == threadpool->limit_worker_min)
1179 *adjustment_interval = (gint)(0.5 + hc->current_sample_interval * (10.0 * MAX (-1.0 * creal (ratio), 1.0)));
1181 *adjustment_interval = hc->current_sample_interval;
1183 return new_thread_count;
1187 heuristic_notify_work_completed (void)
1189 g_assert (threadpool);
1191 InterlockedIncrement (&threadpool->heuristic_completions);
1192 threadpool->heuristic_last_dequeue = mono_msec_ticks ();
1196 heuristic_should_adjust ()
1198 g_assert (threadpool);
1200 if (threadpool->heuristic_last_dequeue > threadpool->heuristic_last_adjustment + threadpool->heuristic_adjustment_interval) {
1201 ThreadPoolCounter counter = COUNTER_READ ();
1202 if (counter._.active <= counter._.max_working)
1212 g_assert (threadpool);
1214 if (mono_mutex_trylock (&threadpool->heuristic_lock) == 0) {
1215 gint32 completions = InterlockedExchange (&threadpool->heuristic_completions, 0);
1216 guint32 sample_end = mono_msec_ticks ();
1217 guint32 sample_duration = sample_end - threadpool->heuristic_sample_start;
1219 if (sample_duration >= threadpool->heuristic_adjustment_interval / 2) {
1220 ThreadPoolCounter counter;
1221 gint16 new_thread_count;
1223 counter = COUNTER_READ ();
1224 new_thread_count = hill_climbing_update (counter._.max_working, sample_duration, completions, &threadpool->heuristic_adjustment_interval);
1226 COUNTER_ATOMIC (counter, { counter._.max_working = new_thread_count; });
1228 if (new_thread_count > counter._.max_working)
1229 worker_request (mono_domain_get ());
1231 threadpool->heuristic_sample_start = sample_end;
1232 threadpool->heuristic_last_adjustment = mono_msec_ticks ();
1235 mono_mutex_unlock (&threadpool->heuristic_lock);
1240 mono_threadpool_ms_cleanup (void)
1242 #ifndef DISABLE_SOCKETS
1243 mono_threadpool_ms_io_cleanup ();
1245 ensure_cleanedup ();
1249 mono_threadpool_ms_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback, MonoObject *state)
1251 static MonoClass *async_call_klass = NULL;
1253 MonoAsyncResult *ares;
1256 if (!async_call_klass)
1257 async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
1258 g_assert (async_call_klass);
1260 ensure_initialized (NULL);
1262 domain = mono_domain_get ();
1264 ac = (MonoAsyncCall*) mono_object_new (domain, async_call_klass);
1265 MONO_OBJECT_SETREF (ac, msg, msg);
1266 MONO_OBJECT_SETREF (ac, state, state);
1268 if (async_callback) {
1269 MONO_OBJECT_SETREF (ac, cb_method, mono_get_delegate_invoke (((MonoObject*) async_callback)->vtable->klass));
1270 MONO_OBJECT_SETREF (ac, cb_target, async_callback);
1273 ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*) ac);
1274 MONO_OBJECT_SETREF (ares, async_delegate, target);
1276 #ifndef DISABLE_SOCKETS
1277 if (mono_threadpool_ms_is_io (target, state))
1278 return mono_threadpool_ms_io_add (ares, (MonoSocketAsyncResult*) state);
1281 mono_threadpool_ms_enqueue_async_result (domain, ares);
1286 mono_threadpool_ms_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1291 g_assert (out_args);
1296 /* check if already finished */
1297 mono_monitor_enter ((MonoObject*) ares);
1299 if (ares->endinvoke_called) {
1300 *exc = (MonoObject*) mono_get_exception_invalid_operation (NULL);
1301 mono_monitor_exit ((MonoObject*) ares);
1305 MONO_OBJECT_SETREF (ares, endinvoke_called, 1);
1307 /* wait until we are really finished */
1308 if (ares->completed) {
1309 mono_monitor_exit ((MonoObject *) ares);
1311 gpointer wait_event;
1313 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle*) ares->handle);
1315 wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1316 g_assert(wait_event);
1317 MONO_OBJECT_SETREF (ares, handle, (MonoObject*) mono_wait_handle_new (mono_object_domain (ares), wait_event));
1319 mono_monitor_exit ((MonoObject*) ares);
1320 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
1323 ac = (MonoAsyncCall*) ares->object_data;
1326 *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1327 *out_args = ac->out_args;
1332 mono_threadpool_ms_remove_domain_jobs (MonoDomain *domain, int timeout)
1334 gboolean res = TRUE;
1339 g_assert (timeout >= -1);
1342 start = mono_msec_ticks ();
1344 #ifndef DISABLE_SOCKETS
1345 mono_threadpool_ms_io_remove_domain_jobs (domain);
1346 if (timeout != -1) {
1347 timeout -= mono_msec_ticks () - start;
1353 * There might be some threads out that could be about to execute stuff from the given domain.
1354 * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
1356 sem = domain->cleanup_semaphore = CreateSemaphore (NULL, 0, 1, NULL);
1359 * The memory barrier here is required to have global ordering between assigning to cleanup_semaphone
1360 * and reading threadpool_jobs. Otherwise this thread could read a stale version of threadpool_jobs
1363 mono_memory_write_barrier ();
1365 while (domain->threadpool_jobs) {
1366 WaitForSingleObject (sem, timeout);
1367 if (timeout != -1) {
1368 timeout -= mono_msec_ticks () - start;
1376 domain->cleanup_semaphore = NULL;
1383 mono_threadpool_ms_suspend (void)
1385 threadpool->suspended = TRUE;
1389 mono_threadpool_ms_resume (void)
1391 threadpool->suspended = FALSE;
1395 ves_icall_System_Threading_MonoRuntimeWorkItem_ExecuteWorkItem (MonoRuntimeWorkItem *rwi)
1397 MonoAsyncResult *ares;
1398 MonoObject *exc = NULL;
1401 ares = rwi->async_result;
1404 mono_async_result_invoke (ares, &exc);
1406 mono_raise_exception ((MonoException*) exc);
1410 ves_icall_System_Threading_Microsoft_ThreadPool_GetAvailableThreadsNative (gint *worker_threads, gint *completion_port_threads)
1412 if (!worker_threads || !completion_port_threads)
1415 ensure_initialized (NULL);
1417 *worker_threads = threadpool->limit_worker_max;
1418 *completion_port_threads = threadpool->limit_io_max;
1422 ves_icall_System_Threading_Microsoft_ThreadPool_GetMinThreadsNative (gint *worker_threads, gint *completion_port_threads)
1424 if (!worker_threads || !completion_port_threads)
1427 ensure_initialized (NULL);
1429 *worker_threads = threadpool->limit_worker_min;
1430 *completion_port_threads = threadpool->limit_io_min;
1434 ves_icall_System_Threading_Microsoft_ThreadPool_GetMaxThreadsNative (gint *worker_threads, gint *completion_port_threads)
1436 if (!worker_threads || !completion_port_threads)
1439 ensure_initialized (NULL);
1441 *worker_threads = threadpool->limit_worker_max;
1442 *completion_port_threads = threadpool->limit_io_max;
1446 ves_icall_System_Threading_Microsoft_ThreadPool_SetMinThreadsNative (gint worker_threads, gint completion_port_threads)
1448 ensure_initialized (NULL);
1450 if (worker_threads <= 0 || worker_threads > threadpool->limit_worker_max)
1452 if (completion_port_threads <= 0 || completion_port_threads > threadpool->limit_io_max)
1455 threadpool->limit_worker_max = worker_threads;
1456 threadpool->limit_io_max = completion_port_threads;
1462 ves_icall_System_Threading_Microsoft_ThreadPool_SetMaxThreadsNative (gint worker_threads, gint completion_port_threads)
1464 gint cpu_count = mono_cpu_count ();
1466 ensure_initialized (NULL);
1468 if (worker_threads < threadpool->limit_worker_min || worker_threads < cpu_count)
1470 if (completion_port_threads < threadpool->limit_io_min || completion_port_threads < cpu_count)
1473 threadpool->limit_worker_max = worker_threads;
1474 threadpool->limit_io_max = completion_port_threads;
1480 ves_icall_System_Threading_Microsoft_ThreadPool_InitializeVMTp (gboolean *enable_worker_tracking)
1482 ensure_initialized (enable_worker_tracking);
1486 ves_icall_System_Threading_Microsoft_ThreadPool_NotifyWorkItemComplete (void)
1488 ThreadPoolCounter counter;
1490 if (mono_domain_is_unloading (mono_domain_get ()) || mono_runtime_is_shutting_down ())
1493 heuristic_notify_work_completed ();
1495 if (heuristic_should_adjust ())
1496 heuristic_adjust ();
1498 counter = COUNTER_READ ();
1499 return counter._.active <= counter._.max_working;
1503 ves_icall_System_Threading_Microsoft_ThreadPool_NotifyWorkItemProgressNative (void)
1505 heuristic_notify_work_completed ();
1507 if (heuristic_should_adjust ())
1508 heuristic_adjust ();
1512 ves_icall_System_Threading_Microsoft_ThreadPool_ReportThreadStatus (gboolean is_working)
1515 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1519 ves_icall_System_Threading_Microsoft_ThreadPool_RequestWorkerThread (void)
1521 return worker_request (mono_domain_get ());
1524 gboolean G_GNUC_UNUSED
1525 ves_icall_System_Threading_Microsoft_ThreadPool_PostQueuedCompletionStatus (MonoNativeOverlapped *native_overlapped)
1527 /* This copy the behavior of the current Mono implementation */
1528 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1532 gboolean G_GNUC_UNUSED
1533 ves_icall_System_Threading_Microsoft_ThreadPool_BindIOCompletionCallbackNative (gpointer file_handle)
1535 /* This copy the behavior of the current Mono implementation */
1539 gboolean G_GNUC_UNUSED
1540 ves_icall_System_Threading_Microsoft_ThreadPool_IsThreadPoolHosted (void)