2 * threadpool-worker.c: native threadpool worker
5 * Ludovic Henry (ludovic.henry@xamarin.com)
7 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
11 #define _USE_MATH_DEFINES // needed by MSVC to define math constants
16 #include <mono/metadata/class-internals.h>
17 #include <mono/metadata/exception.h>
18 #include <mono/metadata/gc-internals.h>
19 #include <mono/metadata/object.h>
20 #include <mono/metadata/object-internals.h>
21 #include <mono/metadata/threadpool.h>
22 #include <mono/metadata/threadpool-worker.h>
23 #include <mono/metadata/threadpool-io.h>
24 #include <mono/metadata/w32event.h>
25 #include <mono/utils/atomic.h>
26 #include <mono/utils/mono-compiler.h>
27 #include <mono/utils/mono-complex.h>
28 #include <mono/utils/mono-logger.h>
29 #include <mono/utils/mono-logger-internals.h>
30 #include <mono/utils/mono-proclib.h>
31 #include <mono/utils/mono-threads.h>
32 #include <mono/utils/mono-time.h>
33 #include <mono/utils/mono-rand.h>
34 #include <mono/utils/refcount.h>
35 #include <mono/utils/w32api.h>
37 #define CPU_USAGE_LOW 80
38 #define CPU_USAGE_HIGH 95
40 #define MONITOR_INTERVAL 500 // ms
41 #define MONITOR_MINIMAL_LIFETIME 60 * 1000 // ms
43 #define WORKER_CREATION_MAX_PER_SEC 10
45 /* The exponent to apply to the gain. 1.0 means to use linear gain,
46 * higher values will enhance large moves and damp small ones.
48 #define HILL_CLIMBING_GAIN_EXPONENT 2.0
50 /* The 'cost' of a thread. 0 means drive for increased throughput regardless
51 * of thread count, higher values bias more against higher thread counts.
53 #define HILL_CLIMBING_BIAS 0.15
55 #define HILL_CLIMBING_WAVE_PERIOD 4
56 #define HILL_CLIMBING_MAX_WAVE_MAGNITUDE 20
57 #define HILL_CLIMBING_WAVE_MAGNITUDE_MULTIPLIER 1.0
58 #define HILL_CLIMBING_WAVE_HISTORY_SIZE 8
59 #define HILL_CLIMBING_TARGET_SIGNAL_TO_NOISE_RATIO 3.0
60 #define HILL_CLIMBING_MAX_CHANGE_PER_SECOND 4
61 #define HILL_CLIMBING_MAX_CHANGE_PER_SAMPLE 20
62 #define HILL_CLIMBING_SAMPLE_INTERVAL_LOW 10
63 #define HILL_CLIMBING_SAMPLE_INTERVAL_HIGH 200
64 #define HILL_CLIMBING_ERROR_SMOOTHING_FACTOR 0.01
65 #define HILL_CLIMBING_MAX_SAMPLE_ERROR_PERCENT 0.15
69 TRANSITION_INITIALIZING,
70 TRANSITION_RANDOM_MOVE,
71 TRANSITION_CLIMBING_MOVE,
72 TRANSITION_CHANGE_POINT,
73 TRANSITION_STABILIZING,
74 TRANSITION_STARVATION,
75 TRANSITION_THREAD_TIMED_OUT,
77 } ThreadPoolHeuristicStateTransition;
81 gint32 samples_to_measure;
82 gdouble target_throughput_ratio;
83 gdouble target_signal_to_noise_ratio;
84 gdouble max_change_per_second;
85 gdouble max_change_per_sample;
86 gint32 max_thread_wave_magnitude;
87 gint32 sample_interval_low;
88 gdouble thread_magnitude_multiplier;
89 gint32 sample_interval_high;
90 gdouble throughput_error_smoothing_factor;
91 gdouble gain_exponent;
92 gdouble max_sample_error;
94 gdouble current_control_setting;
96 gint16 last_thread_count;
97 gdouble elapsed_since_last_change;
98 gdouble completions_since_last_change;
100 gdouble average_throughput_noise;
103 gdouble *thread_counts;
105 guint32 current_sample_interval;
106 gpointer random_interval_generator;
108 gint32 accumulated_completion_count;
109 gdouble accumulated_sample_duration;
110 } ThreadPoolHillClimbing;
113 MonoThreadPoolWorkerCallback callback;
115 } ThreadPoolWorkItem;
119 gint16 max_working; /* determined by heuristic */
120 gint16 starting; /* starting, but not yet in worker_thread */
121 gint16 working; /* executing worker_thread */
122 gint16 parked; /* parked */
125 } ThreadPoolWorkerCounter;
130 ThreadPoolWorkerCounter counters;
132 MonoCoopMutex parked_threads_lock;
133 gint32 parked_threads_count;
134 MonoCoopCond parked_threads_cond;
136 ThreadPoolWorkItem *work_items; // ThreadPoolWorkItem []
137 gint32 work_items_count;
138 gint32 work_items_size;
139 MonoCoopMutex work_items_lock;
141 guint32 worker_creation_current_second;
142 guint32 worker_creation_current_count;
143 MonoCoopMutex worker_creation_lock;
145 gint32 heuristic_completions;
146 gint64 heuristic_sample_start;
147 gint64 heuristic_last_dequeue; // ms
148 gint64 heuristic_last_adjustment; // ms
149 gint64 heuristic_adjustment_interval; // ms
150 ThreadPoolHillClimbing heuristic_hill_climbing;
151 MonoCoopMutex heuristic_lock;
153 gint32 limit_worker_min;
154 gint32 limit_worker_max;
156 MonoCpuUsageState *cpu_usage_state;
159 /* suspended by the debugger */
162 gint32 monitor_status;
166 MONITOR_STATUS_REQUESTED,
167 MONITOR_STATUS_WAITING_FOR_REQUEST,
168 MONITOR_STATUS_NOT_RUNNING,
171 static ThreadPoolWorker worker;
173 #define COUNTER_CHECK(counter) \
175 g_assert (counter._.max_working > 0); \
176 g_assert (counter._.starting >= 0); \
177 g_assert (counter._.working >= 0); \
180 #define COUNTER_ATOMIC(var,block) \
182 ThreadPoolWorkerCounter __old; \
184 __old = COUNTER_READ (); \
187 COUNTER_CHECK (var); \
188 } while (InterlockedCompareExchange64 (&worker.counters.as_gint64, (var).as_gint64, __old.as_gint64) != __old.as_gint64); \
191 static inline ThreadPoolWorkerCounter
194 ThreadPoolWorkerCounter counter;
195 counter.as_gint64 = InterlockedRead64 (&worker.counters.as_gint64);
203 return mono_rand_init (NULL, 0);
207 rand_next (gpointer *handle, guint32 min, guint32 max)
211 mono_rand_try_get_uint32 (handle, &val, min, max, &error);
212 // FIXME handle error
213 mono_error_assert_ok (&error);
218 destroy (gpointer data)
220 mono_coop_mutex_destroy (&worker.parked_threads_lock);
221 mono_coop_cond_destroy (&worker.parked_threads_cond);
223 mono_coop_mutex_destroy (&worker.work_items_lock);
225 mono_coop_mutex_destroy (&worker.worker_creation_lock);
227 mono_coop_mutex_destroy (&worker.heuristic_lock);
229 g_free (worker.cpu_usage_state);
233 mono_threadpool_worker_init (void)
235 ThreadPoolHillClimbing *hc;
236 const char *threads_per_cpu_env;
237 gint threads_per_cpu;
240 mono_refcount_init (&worker, destroy);
242 mono_coop_mutex_init (&worker.parked_threads_lock);
243 worker.parked_threads_count = 0;
244 mono_coop_cond_init (&worker.parked_threads_cond);
246 /* worker.work_items_size is inited to 0 */
247 mono_coop_mutex_init (&worker.work_items_lock);
249 worker.worker_creation_current_second = -1;
250 mono_coop_mutex_init (&worker.worker_creation_lock);
252 worker.heuristic_adjustment_interval = 10;
253 mono_coop_mutex_init (&worker.heuristic_lock);
257 hc = &worker.heuristic_hill_climbing;
259 hc->wave_period = HILL_CLIMBING_WAVE_PERIOD;
260 hc->max_thread_wave_magnitude = HILL_CLIMBING_MAX_WAVE_MAGNITUDE;
261 hc->thread_magnitude_multiplier = (gdouble) HILL_CLIMBING_WAVE_MAGNITUDE_MULTIPLIER;
262 hc->samples_to_measure = hc->wave_period * HILL_CLIMBING_WAVE_HISTORY_SIZE;
263 hc->target_throughput_ratio = (gdouble) HILL_CLIMBING_BIAS;
264 hc->target_signal_to_noise_ratio = (gdouble) HILL_CLIMBING_TARGET_SIGNAL_TO_NOISE_RATIO;
265 hc->max_change_per_second = (gdouble) HILL_CLIMBING_MAX_CHANGE_PER_SECOND;
266 hc->max_change_per_sample = (gdouble) HILL_CLIMBING_MAX_CHANGE_PER_SAMPLE;
267 hc->sample_interval_low = HILL_CLIMBING_SAMPLE_INTERVAL_LOW;
268 hc->sample_interval_high = HILL_CLIMBING_SAMPLE_INTERVAL_HIGH;
269 hc->throughput_error_smoothing_factor = (gdouble) HILL_CLIMBING_ERROR_SMOOTHING_FACTOR;
270 hc->gain_exponent = (gdouble) HILL_CLIMBING_GAIN_EXPONENT;
271 hc->max_sample_error = (gdouble) HILL_CLIMBING_MAX_SAMPLE_ERROR_PERCENT;
272 hc->current_control_setting = 0;
273 hc->total_samples = 0;
274 hc->last_thread_count = 0;
275 hc->average_throughput_noise = 0;
276 hc->elapsed_since_last_change = 0;
277 hc->accumulated_completion_count = 0;
278 hc->accumulated_sample_duration = 0;
279 hc->samples = g_new0 (gdouble, hc->samples_to_measure);
280 hc->thread_counts = g_new0 (gdouble, hc->samples_to_measure);
281 hc->random_interval_generator = rand_create ();
282 hc->current_sample_interval = rand_next (&hc->random_interval_generator, hc->sample_interval_low, hc->sample_interval_high);
284 if (!(threads_per_cpu_env = g_getenv ("MONO_THREADS_PER_CPU")))
287 threads_per_cpu = CLAMP (atoi (threads_per_cpu_env), 1, 50);
289 threads_count = mono_cpu_count () * threads_per_cpu;
291 worker.limit_worker_min = threads_count;
293 #if defined (PLATFORM_ANDROID) || defined (HOST_IOS)
294 worker.limit_worker_max = CLAMP (threads_count * 100, MIN (threads_count, 200), MAX (threads_count, 200));
296 worker.limit_worker_max = threads_count * 100;
299 worker.counters._.max_working = worker.limit_worker_min;
301 worker.cpu_usage_state = g_new0 (MonoCpuUsageState, 1);
303 worker.suspended = FALSE;
305 worker.monitor_status = MONITOR_STATUS_NOT_RUNNING;
309 mono_threadpool_worker_cleanup (void)
311 mono_refcount_dec (&worker);
315 work_item_lock (void)
317 mono_coop_mutex_lock (&worker.work_items_lock);
321 work_item_unlock (void)
323 mono_coop_mutex_unlock (&worker.work_items_lock);
327 work_item_push (MonoThreadPoolWorkerCallback callback, gpointer data)
329 ThreadPoolWorkItem work_item;
333 work_item.callback = callback;
334 work_item.data = data;
338 g_assert (worker.work_items_count <= worker.work_items_size);
340 if (G_UNLIKELY (worker.work_items_count == worker.work_items_size)) {
341 worker.work_items_size += 64;
342 worker.work_items = g_renew (ThreadPoolWorkItem, worker.work_items, worker.work_items_size);
345 g_assert (worker.work_items);
347 worker.work_items [worker.work_items_count ++] = work_item;
349 // printf ("[push] worker.work_items = %p, worker.work_items_count = %d, worker.work_items_size = %d\n",
350 // worker.work_items, worker.work_items_count, worker.work_items_size);
356 work_item_try_pop (ThreadPoolWorkItem *work_item)
358 g_assert (work_item);
362 // printf ("[pop] worker.work_items = %p, worker.work_items_count = %d, worker.work_items_size = %d\n",
363 // worker.work_items, worker.work_items_count, worker.work_items_size);
365 if (worker.work_items_count == 0) {
370 *work_item = worker.work_items [-- worker.work_items_count];
372 if (G_UNLIKELY (worker.work_items_count >= 64 * 3 && worker.work_items_count < worker.work_items_size / 2)) {
373 worker.work_items_size -= 64;
374 worker.work_items = g_renew (ThreadPoolWorkItem, worker.work_items, worker.work_items_size);
383 work_item_count (void)
388 count = worker.work_items_count;
394 static void worker_request (void);
397 mono_threadpool_worker_enqueue (MonoThreadPoolWorkerCallback callback, gpointer data)
399 if (!mono_refcount_tryinc (&worker))
402 work_item_push (callback, data);
406 mono_refcount_dec (&worker);
410 worker_wait_interrupt (gpointer unused)
412 /* If the runtime is not shutting down, we are not using this mechanism to wake up a unparked thread, and if the
413 * runtime is shutting down, then we need to wake up ALL the threads.
414 * It might be a bit wasteful, but I witnessed shutdown hang where the main thread would abort and then wait for all
415 * background threads to exit (see mono_thread_manage). This would go wrong because not all threadpool threads would
416 * be unparked. It would end up getting unstucked because of the timeout, but that would delay shutdown by 5-60s. */
417 if (!mono_runtime_is_shutting_down ())
420 if (!mono_refcount_tryinc (&worker))
423 mono_coop_mutex_lock (&worker.parked_threads_lock);
424 mono_coop_cond_broadcast (&worker.parked_threads_cond);
425 mono_coop_mutex_unlock (&worker.parked_threads_lock);
427 mono_refcount_dec (&worker);
430 /* return TRUE if timeout, FALSE otherwise (worker unpark or interrupt) */
434 gboolean timeout = FALSE;
435 gboolean interrupted = FALSE;
437 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_THREADPOOL, "[%p] worker parking", mono_native_thread_id_get ());
439 mono_coop_mutex_lock (&worker.parked_threads_lock);
441 if (!mono_runtime_is_shutting_down ()) {
442 static gpointer rand_handle = NULL;
443 MonoInternalThread *thread;
444 ThreadPoolWorkerCounter counter;
447 rand_handle = rand_create ();
448 g_assert (rand_handle);
450 thread = mono_thread_internal_current ();
453 COUNTER_ATOMIC (counter, {
454 counter._.working --;
458 worker.parked_threads_count += 1;
460 mono_thread_info_install_interrupt (worker_wait_interrupt, NULL, &interrupted);
464 if (mono_coop_cond_timedwait (&worker.parked_threads_cond, &worker.parked_threads_lock, rand_next (&rand_handle, 5 * 1000, 60 * 1000)) != 0)
467 mono_thread_info_uninstall_interrupt (&interrupted);
470 worker.parked_threads_count -= 1;
472 COUNTER_ATOMIC (counter, {
473 counter._.working ++;
478 mono_coop_mutex_unlock (&worker.parked_threads_lock);
480 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_THREADPOOL, "[%p] worker unparking, timeout? %s interrupted? %s",
481 mono_native_thread_id_get (), timeout ? "yes" : "no", interrupted ? "yes" : "no");
487 worker_try_unpark (void)
489 gboolean res = FALSE;
491 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try unpark worker", mono_native_thread_id_get ());
493 mono_coop_mutex_lock (&worker.parked_threads_lock);
494 if (worker.parked_threads_count > 0) {
495 mono_coop_cond_signal (&worker.parked_threads_cond);
498 mono_coop_mutex_unlock (&worker.parked_threads_lock);
500 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try unpark worker, success? %s", mono_native_thread_id_get (), res ? "yes" : "no");
506 worker_thread (gpointer unused)
508 MonoInternalThread *thread;
509 ThreadPoolWorkerCounter counter;
511 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_THREADPOOL, "[%p] worker starting", mono_native_thread_id_get ());
513 if (!mono_refcount_tryinc (&worker))
516 COUNTER_ATOMIC (counter, {
517 counter._.starting --;
518 counter._.working ++;
521 thread = mono_thread_internal_current ();
524 while (!mono_runtime_is_shutting_down ()) {
525 ThreadPoolWorkItem work_item;
527 if (mono_thread_interruption_checkpoint ())
530 if (!work_item_try_pop (&work_item)) {
533 timeout = worker_park ();
540 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] worker executing %p (%p)",
541 mono_native_thread_id_get (), work_item.callback, work_item.data);
543 work_item.callback (work_item.data);
546 COUNTER_ATOMIC (counter, {
547 counter._.working --;
550 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_THREADPOOL, "[%p] worker finishing", mono_native_thread_id_get ());
552 mono_refcount_dec (&worker);
558 worker_try_create (void)
561 MonoInternalThread *thread;
562 gint64 current_ticks;
564 ThreadPoolWorkerCounter counter;
566 if (mono_runtime_is_shutting_down ())
569 mono_coop_mutex_lock (&worker.worker_creation_lock);
571 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker", mono_native_thread_id_get ());
573 current_ticks = mono_100ns_ticks ();
574 if (0 == current_ticks) {
575 g_warning ("failed to get 100ns ticks");
577 now = current_ticks / (10 * 1000 * 1000);
578 if (worker.worker_creation_current_second != now) {
579 worker.worker_creation_current_second = now;
580 worker.worker_creation_current_count = 0;
582 g_assert (worker.worker_creation_current_count <= WORKER_CREATION_MAX_PER_SEC);
583 if (worker.worker_creation_current_count == WORKER_CREATION_MAX_PER_SEC) {
584 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",
585 mono_native_thread_id_get (), worker.worker_creation_current_count);
586 mono_coop_mutex_unlock (&worker.worker_creation_lock);
592 COUNTER_ATOMIC (counter, {
593 if (counter._.working >= counter._.max_working) {
594 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker, failed: maximum number of working threads reached",
595 mono_native_thread_id_get ());
596 mono_coop_mutex_unlock (&worker.worker_creation_lock);
599 counter._.starting ++;
602 thread = mono_thread_create_internal (mono_get_root_domain (), worker_thread, NULL, TRUE, 0, &error);
604 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker, failed: could not create thread due to %s", mono_native_thread_id_get (), mono_error_get_message (&error));
605 mono_error_cleanup (&error);
607 COUNTER_ATOMIC (counter, {
608 counter._.starting --;
611 mono_coop_mutex_unlock (&worker.worker_creation_lock);
616 worker.worker_creation_current_count += 1;
618 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker, created %p, now = %d count = %d",
619 mono_native_thread_id_get (), (gpointer) thread->tid, now, worker.worker_creation_current_count);
621 mono_coop_mutex_unlock (&worker.worker_creation_lock);
625 static void monitor_ensure_running (void);
628 worker_request (void)
630 if (worker.suspended)
633 monitor_ensure_running ();
635 if (worker_try_unpark ()) {
636 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] request worker, unparked", mono_native_thread_id_get ());
640 if (worker_try_create ()) {
641 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] request worker, created", mono_native_thread_id_get ());
645 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] request worker, failed", mono_native_thread_id_get ());
649 monitor_should_keep_running (void)
651 static gint64 last_should_keep_running = -1;
653 g_assert (worker.monitor_status == MONITOR_STATUS_WAITING_FOR_REQUEST || worker.monitor_status == MONITOR_STATUS_REQUESTED);
655 if (InterlockedExchange (&worker.monitor_status, MONITOR_STATUS_WAITING_FOR_REQUEST) == MONITOR_STATUS_WAITING_FOR_REQUEST) {
656 gboolean should_keep_running = TRUE, force_should_keep_running = FALSE;
658 if (mono_runtime_is_shutting_down ()) {
659 should_keep_running = FALSE;
661 if (work_item_count () == 0)
662 should_keep_running = FALSE;
664 if (!should_keep_running) {
665 if (last_should_keep_running == -1 || mono_100ns_ticks () - last_should_keep_running < MONITOR_MINIMAL_LIFETIME * 1000 * 10) {
666 should_keep_running = force_should_keep_running = TRUE;
671 if (should_keep_running) {
672 if (last_should_keep_running == -1 || !force_should_keep_running)
673 last_should_keep_running = mono_100ns_ticks ();
675 last_should_keep_running = -1;
676 if (InterlockedCompareExchange (&worker.monitor_status, MONITOR_STATUS_NOT_RUNNING, MONITOR_STATUS_WAITING_FOR_REQUEST) == MONITOR_STATUS_WAITING_FOR_REQUEST)
681 g_assert (worker.monitor_status == MONITOR_STATUS_WAITING_FOR_REQUEST || worker.monitor_status == MONITOR_STATUS_REQUESTED);
687 monitor_sufficient_delay_since_last_dequeue (void)
691 if (worker.cpu_usage < CPU_USAGE_LOW) {
692 threshold = MONITOR_INTERVAL;
694 ThreadPoolWorkerCounter counter;
695 counter = COUNTER_READ ();
696 threshold = counter._.max_working * MONITOR_INTERVAL * 2;
699 return mono_msec_ticks () >= worker.heuristic_last_dequeue + threshold;
702 static void hill_climbing_force_change (gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition);
705 monitor_thread (gpointer unused)
707 MonoInternalThread *internal;
710 if (!mono_refcount_tryinc (&worker))
713 internal = mono_thread_internal_current ();
716 mono_cpu_usage (worker.cpu_usage_state);
718 // printf ("monitor_thread: start\n");
720 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, started", mono_native_thread_id_get ());
723 ThreadPoolWorkerCounter counter;
724 gboolean limit_worker_max_reached;
725 gint32 interval_left = MONITOR_INTERVAL;
726 gint32 awake = 0; /* number of spurious awakes we tolerate before doing a round of rebalancing */
728 g_assert (worker.monitor_status != MONITOR_STATUS_NOT_RUNNING);
730 // counter = COUNTER_READ ();
731 // printf ("monitor_thread: starting = %d working = %d parked = %d max_working = %d\n",
732 // counter._.starting, counter._.working, counter._.parked, counter._.max_working);
736 gboolean alerted = FALSE;
738 if (mono_runtime_is_shutting_down ())
741 ts = mono_msec_ticks ();
742 if (mono_thread_info_sleep (interval_left, &alerted) == 0)
744 interval_left -= mono_msec_ticks () - ts;
746 g_assert (!(internal->state & ThreadState_StopRequested));
747 mono_thread_interruption_checkpoint ();
748 } while (interval_left > 0 && ++awake < 10);
750 if (mono_runtime_is_shutting_down ())
753 if (worker.suspended)
756 if (work_item_count () == 0)
759 worker.cpu_usage = mono_cpu_usage (worker.cpu_usage_state);
761 if (!monitor_sufficient_delay_since_last_dequeue ())
764 limit_worker_max_reached = FALSE;
766 COUNTER_ATOMIC (counter, {
767 if (counter._.max_working >= worker.limit_worker_max) {
768 limit_worker_max_reached = TRUE;
771 counter._.max_working ++;
774 if (limit_worker_max_reached)
777 hill_climbing_force_change (counter._.max_working, TRANSITION_STARVATION);
779 for (i = 0; i < 5; ++i) {
780 if (mono_runtime_is_shutting_down ())
783 if (worker_try_unpark ()) {
784 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, unparked", mono_native_thread_id_get ());
788 if (worker_try_create ()) {
789 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, created", mono_native_thread_id_get ());
793 } while (monitor_should_keep_running ());
795 // printf ("monitor_thread: stop\n");
797 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, finished", mono_native_thread_id_get ());
799 mono_refcount_dec (&worker);
804 monitor_ensure_running (void)
808 switch (worker.monitor_status) {
809 case MONITOR_STATUS_REQUESTED:
810 // printf ("monitor_thread: requested\n");
812 case MONITOR_STATUS_WAITING_FOR_REQUEST:
813 // printf ("monitor_thread: waiting for request\n");
814 InterlockedCompareExchange (&worker.monitor_status, MONITOR_STATUS_REQUESTED, MONITOR_STATUS_WAITING_FOR_REQUEST);
816 case MONITOR_STATUS_NOT_RUNNING:
817 // printf ("monitor_thread: not running\n");
818 if (mono_runtime_is_shutting_down ())
820 if (InterlockedCompareExchange (&worker.monitor_status, MONITOR_STATUS_REQUESTED, MONITOR_STATUS_NOT_RUNNING) == MONITOR_STATUS_NOT_RUNNING) {
821 // printf ("monitor_thread: creating\n");
822 if (!mono_thread_create_internal (mono_get_root_domain (), monitor_thread, NULL, TRUE, SMALL_STACK, &error)) {
823 // printf ("monitor_thread: creating failed\n");
824 worker.monitor_status = MONITOR_STATUS_NOT_RUNNING;
825 mono_error_cleanup (&error);
826 mono_refcount_dec (&worker);
831 default: g_assert_not_reached ();
837 hill_climbing_change_thread_count (gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition)
839 ThreadPoolHillClimbing *hc;
841 hc = &worker.heuristic_hill_climbing;
843 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] hill climbing, change max number of threads %d", mono_native_thread_id_get (), new_thread_count);
845 hc->last_thread_count = new_thread_count;
846 hc->current_sample_interval = rand_next (&hc->random_interval_generator, hc->sample_interval_low, hc->sample_interval_high);
847 hc->elapsed_since_last_change = 0;
848 hc->completions_since_last_change = 0;
852 hill_climbing_force_change (gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition)
854 ThreadPoolHillClimbing *hc;
856 hc = &worker.heuristic_hill_climbing;
858 if (new_thread_count != hc->last_thread_count) {
859 hc->current_control_setting += new_thread_count - hc->last_thread_count;
860 hill_climbing_change_thread_count (new_thread_count, transition);
864 static double_complex
865 hill_climbing_get_wave_component (gdouble *samples, guint sample_count, gdouble period)
867 ThreadPoolHillClimbing *hc;
868 gdouble w, cosine, sine, coeff, q0, q1, q2;
871 g_assert (sample_count >= period);
872 g_assert (period >= 2);
874 hc = &worker.heuristic_hill_climbing;
876 w = 2.0 * M_PI / period;
879 coeff = 2.0 * cosine;
882 for (i = 0; i < sample_count; ++i) {
883 q0 = coeff * q1 - q2 + samples [(hc->total_samples - sample_count + i) % hc->samples_to_measure];
888 return mono_double_complex_scalar_div (mono_double_complex_make (q1 - q2 * cosine, (q2 * sine)), ((gdouble)sample_count));
892 hill_climbing_update (gint16 current_thread_count, guint32 sample_duration, gint32 completions, gint64 *adjustment_interval)
894 ThreadPoolHillClimbing *hc;
895 ThreadPoolHeuristicStateTransition transition;
897 gdouble throughput_error_estimate;
903 gint new_thread_wave_magnitude;
904 gint new_thread_count;
905 double_complex thread_wave_component;
906 double_complex throughput_wave_component;
907 double_complex ratio;
909 g_assert (adjustment_interval);
911 hc = &worker.heuristic_hill_climbing;
913 /* If someone changed the thread count without telling us, update our records accordingly. */
914 if (current_thread_count != hc->last_thread_count)
915 hill_climbing_force_change (current_thread_count, TRANSITION_INITIALIZING);
917 /* Update the cumulative stats for this thread count */
918 hc->elapsed_since_last_change += sample_duration;
919 hc->completions_since_last_change += completions;
921 /* Add in any data we've already collected about this sample */
922 sample_duration += hc->accumulated_sample_duration;
923 completions += hc->accumulated_completion_count;
925 /* We need to make sure we're collecting reasonably accurate data. Since we're just counting the end
926 * of each work item, we are goinng to be missing some data about what really happened during the
927 * sample interval. The count produced by each thread includes an initial work item that may have
928 * started well before the start of the interval, and each thread may have been running some new
929 * work item for some time before the end of the interval, which did not yet get counted. So
930 * our count is going to be off by +/- threadCount workitems.
932 * The exception is that the thread that reported to us last time definitely wasn't running any work
933 * at that time, and the thread that's reporting now definitely isn't running a work item now. So
934 * we really only need to consider threadCount-1 threads.
936 * Thus the percent error in our count is +/- (threadCount-1)/numCompletions.
938 * We cannot rely on the frequency-domain analysis we'll be doing later to filter out this error, because
939 * of the way it accumulates over time. If this sample is off by, say, 33% in the negative direction,
940 * then the next one likely will be too. The one after that will include the sum of the completions
941 * we missed in the previous samples, and so will be 33% positive. So every three samples we'll have
942 * two "low" samples and one "high" sample. This will appear as periodic variation right in the frequency
943 * range we're targeting, which will not be filtered by the frequency-domain translation. */
944 if (hc->total_samples > 0 && ((current_thread_count - 1.0) / completions) >= hc->max_sample_error) {
945 /* Not accurate enough yet. Let's accumulate the data so
946 * far, and tell the ThreadPoolWorker to collect a little more. */
947 hc->accumulated_sample_duration = sample_duration;
948 hc->accumulated_completion_count = completions;
949 *adjustment_interval = 10;
950 return current_thread_count;
953 /* We've got enouugh data for our sample; reset our accumulators for next time. */
954 hc->accumulated_sample_duration = 0;
955 hc->accumulated_completion_count = 0;
957 /* Add the current thread count and throughput sample to our history. */
958 throughput = ((gdouble) completions) / sample_duration;
960 sample_index = hc->total_samples % hc->samples_to_measure;
961 hc->samples [sample_index] = throughput;
962 hc->thread_counts [sample_index] = current_thread_count;
963 hc->total_samples ++;
965 /* Set up defaults for our metrics. */
966 thread_wave_component = mono_double_complex_make(0, 0);
967 throughput_wave_component = mono_double_complex_make(0, 0);
968 throughput_error_estimate = 0;
969 ratio = mono_double_complex_make(0, 0);
972 transition = TRANSITION_WARMUP;
974 /* How many samples will we use? It must be at least the three wave periods we're looking for, and it must also
975 * be a whole multiple of the primary wave's period; otherwise the frequency we're looking for will fall between
976 * two frequency bands in the Fourier analysis, and we won't be able to measure it accurately. */
977 sample_count = ((gint) MIN (hc->total_samples - 1, hc->samples_to_measure) / hc->wave_period) * hc->wave_period;
979 if (sample_count > hc->wave_period) {
981 gdouble average_throughput;
982 gdouble average_thread_count;
983 gdouble sample_sum = 0;
984 gdouble thread_sum = 0;
986 /* Average the throughput and thread count samples, so we can scale the wave magnitudes later. */
987 for (i = 0; i < sample_count; ++i) {
988 guint j = (hc->total_samples - sample_count + i) % hc->samples_to_measure;
989 sample_sum += hc->samples [j];
990 thread_sum += hc->thread_counts [j];
993 average_throughput = sample_sum / sample_count;
994 average_thread_count = thread_sum / sample_count;
996 if (average_throughput > 0 && average_thread_count > 0) {
997 gdouble noise_for_confidence, adjacent_period_1, adjacent_period_2;
999 /* Calculate the periods of the adjacent frequency bands we'll be using to
1000 * measure noise levels. We want the two adjacent Fourier frequency bands. */
1001 adjacent_period_1 = sample_count / (((gdouble) sample_count) / ((gdouble) hc->wave_period) + 1);
1002 adjacent_period_2 = sample_count / (((gdouble) sample_count) / ((gdouble) hc->wave_period) - 1);
1004 /* Get the the three different frequency components of the throughput (scaled by average
1005 * throughput). Our "error" estimate (the amount of noise that might be present in the
1006 * frequency band we're really interested in) is the average of the adjacent bands. */
1007 throughput_wave_component = mono_double_complex_scalar_div (hill_climbing_get_wave_component (hc->samples, sample_count, hc->wave_period), average_throughput);
1008 throughput_error_estimate = cabs (mono_double_complex_scalar_div (hill_climbing_get_wave_component (hc->samples, sample_count, adjacent_period_1), average_throughput));
1010 if (adjacent_period_2 <= sample_count) {
1011 throughput_error_estimate = MAX (throughput_error_estimate, cabs (mono_double_complex_scalar_div (hill_climbing_get_wave_component (
1012 hc->samples, sample_count, adjacent_period_2), average_throughput)));
1015 /* Do the same for the thread counts, so we have something to compare to. We don't
1016 * measure thread count noise, because there is none; these are exact measurements. */
1017 thread_wave_component = mono_double_complex_scalar_div (hill_climbing_get_wave_component (hc->thread_counts, sample_count, hc->wave_period), average_thread_count);
1019 /* Update our moving average of the throughput noise. We'll use this
1020 * later as feedback to determine the new size of the thread wave. */
1021 if (hc->average_throughput_noise == 0) {
1022 hc->average_throughput_noise = throughput_error_estimate;
1024 hc->average_throughput_noise = (hc->throughput_error_smoothing_factor * throughput_error_estimate)
1025 + ((1.0 + hc->throughput_error_smoothing_factor) * hc->average_throughput_noise);
1028 if (cabs (thread_wave_component) > 0) {
1029 /* Adjust the throughput wave so it's centered around the target wave,
1030 * and then calculate the adjusted throughput/thread ratio. */
1031 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);
1032 transition = TRANSITION_CLIMBING_MOVE;
1034 ratio = mono_double_complex_make (0, 0);
1035 transition = TRANSITION_STABILIZING;
1038 noise_for_confidence = MAX (hc->average_throughput_noise, throughput_error_estimate);
1039 if (noise_for_confidence > 0) {
1040 confidence = cabs (thread_wave_component) / noise_for_confidence / hc->target_signal_to_noise_ratio;
1042 /* there is no noise! */
1048 /* We use just the real part of the complex ratio we just calculated. If the throughput signal
1049 * is exactly in phase with the thread signal, this will be the same as taking the magnitude of
1050 * the complex move and moving that far up. If they're 180 degrees out of phase, we'll move
1051 * backward (because this indicates that our changes are having the opposite of the intended effect).
1052 * If they're 90 degrees out of phase, we won't move at all, because we can't tell wether we're
1053 * having a negative or positive effect on throughput. */
1054 move = creal (ratio);
1055 move = CLAMP (move, -1.0, 1.0);
1057 /* Apply our confidence multiplier. */
1058 move *= CLAMP (confidence, -1.0, 1.0);
1060 /* Now apply non-linear gain, such that values around zero are attenuated, while higher values
1061 * are enhanced. This allows us to move quickly if we're far away from the target, but more slowly
1062 * if we're getting close, giving us rapid ramp-up without wild oscillations around the target. */
1063 gain = hc->max_change_per_second * sample_duration;
1064 move = pow (fabs (move), hc->gain_exponent) * (move >= 0.0 ? 1 : -1) * gain;
1065 move = MIN (move, hc->max_change_per_sample);
1067 /* If the result was positive, and CPU is > 95%, refuse the move. */
1068 if (move > 0.0 && worker.cpu_usage > CPU_USAGE_HIGH)
1071 /* Apply the move to our control setting. */
1072 hc->current_control_setting += move;
1074 /* Calculate the new thread wave magnitude, which is based on the moving average we've been keeping of the
1075 * throughput error. This average starts at zero, so we'll start with a nice safe little wave at first. */
1076 new_thread_wave_magnitude = (gint)(0.5 + (hc->current_control_setting * hc->average_throughput_noise
1077 * hc->target_signal_to_noise_ratio * hc->thread_magnitude_multiplier * 2.0));
1078 new_thread_wave_magnitude = CLAMP (new_thread_wave_magnitude, 1, hc->max_thread_wave_magnitude);
1080 /* Make sure our control setting is within the ThreadPoolWorker's limits. */
1081 hc->current_control_setting = CLAMP (hc->current_control_setting, worker.limit_worker_min, worker.limit_worker_max - new_thread_wave_magnitude);
1083 /* Calculate the new thread count (control setting + square wave). */
1084 new_thread_count = (gint)(hc->current_control_setting + new_thread_wave_magnitude * ((hc->total_samples / (hc->wave_period / 2)) % 2));
1086 /* Make sure the new thread count doesn't exceed the ThreadPoolWorker's limits. */
1087 new_thread_count = CLAMP (new_thread_count, worker.limit_worker_min, worker.limit_worker_max);
1089 if (new_thread_count != current_thread_count)
1090 hill_climbing_change_thread_count (new_thread_count, transition);
1092 if (creal (ratio) < 0.0 && new_thread_count == worker.limit_worker_min)
1093 *adjustment_interval = (gint)(0.5 + hc->current_sample_interval * (10.0 * MAX (-1.0 * creal (ratio), 1.0)));
1095 *adjustment_interval = hc->current_sample_interval;
1097 return new_thread_count;
1101 heuristic_should_adjust (void)
1103 if (worker.heuristic_last_dequeue > worker.heuristic_last_adjustment + worker.heuristic_adjustment_interval) {
1104 ThreadPoolWorkerCounter counter;
1105 counter = COUNTER_READ ();
1106 if (counter._.working <= counter._.max_working)
1114 heuristic_adjust (void)
1116 if (mono_coop_mutex_trylock (&worker.heuristic_lock) == 0) {
1117 gint32 completions = InterlockedExchange (&worker.heuristic_completions, 0);
1118 gint64 sample_end = mono_msec_ticks ();
1119 gint64 sample_duration = sample_end - worker.heuristic_sample_start;
1121 if (sample_duration >= worker.heuristic_adjustment_interval / 2) {
1122 ThreadPoolWorkerCounter counter;
1123 gint16 new_thread_count;
1125 counter = COUNTER_READ ();
1126 new_thread_count = hill_climbing_update (counter._.max_working, sample_duration, completions, &worker.heuristic_adjustment_interval);
1128 COUNTER_ATOMIC (counter, {
1129 counter._.max_working = new_thread_count;
1132 if (new_thread_count > counter._.max_working)
1135 worker.heuristic_sample_start = sample_end;
1136 worker.heuristic_last_adjustment = mono_msec_ticks ();
1139 mono_coop_mutex_unlock (&worker.heuristic_lock);
1144 heuristic_notify_work_completed (void)
1146 InterlockedIncrement (&worker.heuristic_completions);
1147 worker.heuristic_last_dequeue = mono_msec_ticks ();
1149 if (heuristic_should_adjust ())
1150 heuristic_adjust ();
1154 mono_threadpool_worker_notify_completed (void)
1156 ThreadPoolWorkerCounter counter;
1158 heuristic_notify_work_completed ();
1160 counter = COUNTER_READ ();
1161 return counter._.working <= counter._.max_working;
1165 mono_threadpool_worker_get_min (void)
1169 if (!mono_refcount_tryinc (&worker))
1172 ret = worker.limit_worker_min;
1174 mono_refcount_dec (&worker);
1179 mono_threadpool_worker_set_min (gint32 value)
1181 if (value <= 0 || value > worker.limit_worker_max)
1184 if (!mono_refcount_tryinc (&worker))
1187 worker.limit_worker_min = value;
1189 mono_refcount_dec (&worker);
1194 mono_threadpool_worker_get_max (void)
1198 if (!mono_refcount_tryinc (&worker))
1201 ret = worker.limit_worker_max;
1203 mono_refcount_dec (&worker);
1208 mono_threadpool_worker_set_max (gint32 value)
1212 cpu_count = mono_cpu_count ();
1213 if (value < worker.limit_worker_min || value < cpu_count)
1216 if (!mono_refcount_tryinc (&worker))
1219 worker.limit_worker_max = value;
1221 mono_refcount_dec (&worker);
1226 mono_threadpool_worker_set_suspended (gboolean suspended)
1228 if (!mono_refcount_tryinc (&worker))
1231 worker.suspended = suspended;
1235 mono_refcount_dec (&worker);