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-lazy-init.h>
29 #include <mono/utils/mono-logger.h>
30 #include <mono/utils/mono-logger-internals.h>
31 #include <mono/utils/mono-proclib.h>
32 #include <mono/utils/mono-threads.h>
33 #include <mono/utils/mono-time.h>
34 #include <mono/utils/mono-rand.h>
35 #include <mono/utils/refcount.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;
127 typedef MonoInternalThread ThreadPoolWorkerThread;
129 struct MonoThreadPoolWorker {
132 ThreadPoolWorkerCounter counters;
134 GPtrArray *threads; // ThreadPoolWorkerThread* []
135 MonoCoopMutex threads_lock; /* protect access to working_threads and parked_threads */
136 gint32 parked_threads_count;
137 MonoCoopCond parked_threads_cond;
138 MonoCoopCond threads_exit_cond;
140 ThreadPoolWorkItem *work_items; // ThreadPoolWorkItem []
141 gint32 work_items_count;
142 gint32 work_items_size;
143 MonoCoopMutex work_items_lock;
145 guint32 worker_creation_current_second;
146 guint32 worker_creation_current_count;
147 MonoCoopMutex worker_creation_lock;
149 gint32 heuristic_completions;
150 gint64 heuristic_sample_start;
151 gint64 heuristic_last_dequeue; // ms
152 gint64 heuristic_last_adjustment; // ms
153 gint64 heuristic_adjustment_interval; // ms
154 ThreadPoolHillClimbing heuristic_hill_climbing;
155 MonoCoopMutex heuristic_lock;
157 gint32 limit_worker_min;
158 gint32 limit_worker_max;
160 MonoCpuUsageState *cpu_usage_state;
163 /* suspended by the debugger */
166 gint32 monitor_status;
170 MONITOR_STATUS_REQUESTED,
171 MONITOR_STATUS_WAITING_FOR_REQUEST,
172 MONITOR_STATUS_NOT_RUNNING,
175 #define COUNTER_CHECK(counter) \
177 g_assert (counter._.max_working > 0); \
178 g_assert (counter._.starting >= 0); \
179 g_assert (counter._.working >= 0); \
182 #define COUNTER_ATOMIC(worker,var,block) \
184 ThreadPoolWorkerCounter __old; \
187 __old = COUNTER_READ (worker); \
190 COUNTER_CHECK (var); \
191 } while (InterlockedCompareExchange64 (&worker->counters.as_gint64, (var).as_gint64, __old.as_gint64) != __old.as_gint64); \
194 static inline ThreadPoolWorkerCounter
195 COUNTER_READ (MonoThreadPoolWorker *worker)
197 ThreadPoolWorkerCounter counter;
198 counter.as_gint64 = InterlockedRead64 (&worker->counters.as_gint64);
206 return mono_rand_init (NULL, 0);
210 rand_next (gpointer *handle, guint32 min, guint32 max)
214 mono_rand_try_get_uint32 (handle, &val, min, max, &error);
215 // FIXME handle error
216 mono_error_assert_ok (&error);
221 destroy (gpointer data)
223 MonoThreadPoolWorker *worker;
225 worker = (MonoThreadPoolWorker*) data;
228 // FIXME destroy everything
234 mono_threadpool_worker_init (MonoThreadPoolWorker **worker)
236 MonoThreadPoolWorker *wk;
237 ThreadPoolHillClimbing *hc;
238 const char *threads_per_cpu_env;
239 gint threads_per_cpu;
244 wk = *worker = g_new0 (MonoThreadPoolWorker, 1);
246 mono_refcount_init (wk, destroy);
248 wk->threads = g_ptr_array_new ();
249 mono_coop_mutex_init (&wk->threads_lock);
250 wk->parked_threads_count = 0;
251 mono_coop_cond_init (&wk->parked_threads_cond);
252 mono_coop_cond_init (&wk->threads_exit_cond);
254 /* wk->work_items_size is inited to 0 */
255 mono_coop_mutex_init (&wk->work_items_lock);
257 wk->worker_creation_current_second = -1;
258 mono_coop_mutex_init (&wk->worker_creation_lock);
260 wk->heuristic_adjustment_interval = 10;
261 mono_coop_mutex_init (&wk->heuristic_lock);
265 hc = &wk->heuristic_hill_climbing;
267 hc->wave_period = HILL_CLIMBING_WAVE_PERIOD;
268 hc->max_thread_wave_magnitude = HILL_CLIMBING_MAX_WAVE_MAGNITUDE;
269 hc->thread_magnitude_multiplier = (gdouble) HILL_CLIMBING_WAVE_MAGNITUDE_MULTIPLIER;
270 hc->samples_to_measure = hc->wave_period * HILL_CLIMBING_WAVE_HISTORY_SIZE;
271 hc->target_throughput_ratio = (gdouble) HILL_CLIMBING_BIAS;
272 hc->target_signal_to_noise_ratio = (gdouble) HILL_CLIMBING_TARGET_SIGNAL_TO_NOISE_RATIO;
273 hc->max_change_per_second = (gdouble) HILL_CLIMBING_MAX_CHANGE_PER_SECOND;
274 hc->max_change_per_sample = (gdouble) HILL_CLIMBING_MAX_CHANGE_PER_SAMPLE;
275 hc->sample_interval_low = HILL_CLIMBING_SAMPLE_INTERVAL_LOW;
276 hc->sample_interval_high = HILL_CLIMBING_SAMPLE_INTERVAL_HIGH;
277 hc->throughput_error_smoothing_factor = (gdouble) HILL_CLIMBING_ERROR_SMOOTHING_FACTOR;
278 hc->gain_exponent = (gdouble) HILL_CLIMBING_GAIN_EXPONENT;
279 hc->max_sample_error = (gdouble) HILL_CLIMBING_MAX_SAMPLE_ERROR_PERCENT;
280 hc->current_control_setting = 0;
281 hc->total_samples = 0;
282 hc->last_thread_count = 0;
283 hc->average_throughput_noise = 0;
284 hc->elapsed_since_last_change = 0;
285 hc->accumulated_completion_count = 0;
286 hc->accumulated_sample_duration = 0;
287 hc->samples = g_new0 (gdouble, hc->samples_to_measure);
288 hc->thread_counts = g_new0 (gdouble, hc->samples_to_measure);
289 hc->random_interval_generator = rand_create ();
290 hc->current_sample_interval = rand_next (&hc->random_interval_generator, hc->sample_interval_low, hc->sample_interval_high);
292 if (!(threads_per_cpu_env = g_getenv ("MONO_THREADS_PER_CPU")))
295 threads_per_cpu = CLAMP (atoi (threads_per_cpu_env), 1, 50);
297 threads_count = mono_cpu_count () * threads_per_cpu;
299 wk->limit_worker_min = threads_count;
301 #if defined (PLATFORM_ANDROID) || defined (HOST_IOS)
302 wk->limit_worker_max = CLAMP (threads_count * 100, MIN (threads_count, 200), MAX (threads_count, 200));
304 wk->limit_worker_max = threads_count * 100;
307 wk->counters._.max_working = wk->limit_worker_min;
309 wk->cpu_usage_state = g_new0 (MonoCpuUsageState, 1);
311 wk->suspended = FALSE;
313 wk->monitor_status = MONITOR_STATUS_NOT_RUNNING;
317 mono_threadpool_worker_cleanup (MonoThreadPoolWorker *worker)
319 MonoInternalThread *current;
321 /* we make the assumption along the code that we are
322 * cleaning up only if the runtime is shutting down */
323 g_assert (mono_runtime_is_shutting_down ());
325 current = mono_thread_internal_current ();
327 while (worker->monitor_status != MONITOR_STATUS_NOT_RUNNING)
328 mono_thread_info_sleep (1, NULL);
330 mono_coop_mutex_lock (&worker->threads_lock);
332 /* unpark all worker->parked_threads */
333 mono_coop_cond_broadcast (&worker->parked_threads_cond);
336 ThreadPoolWorkerCounter counter;
338 counter = COUNTER_READ (worker);
339 if (counter._.starting + counter._.working + counter._.parked == 0)
342 if (counter._.starting + counter._.working + counter._.parked == 1) {
343 if (worker->threads->len == 1 && g_ptr_array_index (worker->threads, 0) == current) {
344 /* We are waiting on ourselves */
349 mono_coop_cond_wait (&worker->threads_exit_cond, &worker->threads_lock);
352 mono_coop_mutex_unlock (&worker->threads_lock);
354 mono_refcount_dec (worker);
358 work_item_lock (MonoThreadPoolWorker *worker)
360 mono_coop_mutex_lock (&worker->work_items_lock);
364 work_item_unlock (MonoThreadPoolWorker *worker)
366 mono_coop_mutex_unlock (&worker->work_items_lock);
370 work_item_push (MonoThreadPoolWorker *worker, MonoThreadPoolWorkerCallback callback, gpointer data)
372 ThreadPoolWorkItem work_item;
377 work_item.callback = callback;
378 work_item.data = data;
380 work_item_lock (worker);
382 g_assert (worker->work_items_count <= worker->work_items_size);
384 if (G_UNLIKELY (worker->work_items_count == worker->work_items_size)) {
385 worker->work_items_size += 64;
386 worker->work_items = g_renew (ThreadPoolWorkItem, worker->work_items, worker->work_items_size);
389 g_assert (worker->work_items);
391 worker->work_items [worker->work_items_count ++] = work_item;
393 // printf ("[push] worker->work_items = %p, worker->work_items_count = %d, worker->work_items_size = %d\n",
394 // worker->work_items, worker->work_items_count, worker->work_items_size);
396 work_item_unlock (worker);
400 work_item_try_pop (MonoThreadPoolWorker *worker, ThreadPoolWorkItem *work_item)
403 g_assert (work_item);
405 work_item_lock (worker);
407 // printf ("[pop] worker->work_items = %p, worker->work_items_count = %d, worker->work_items_size = %d\n",
408 // worker->work_items, worker->work_items_count, worker->work_items_size);
410 if (worker->work_items_count == 0) {
411 work_item_unlock (worker);
415 *work_item = worker->work_items [-- worker->work_items_count];
417 if (G_UNLIKELY (worker->work_items_count >= 64 * 3 && worker->work_items_count < worker->work_items_size / 2)) {
418 worker->work_items_size -= 64;
419 worker->work_items = g_renew (ThreadPoolWorkItem, worker->work_items, worker->work_items_size);
422 work_item_unlock (worker);
428 work_item_count (MonoThreadPoolWorker *worker)
432 work_item_lock (worker);
433 count = worker->work_items_count;
434 work_item_unlock (worker);
439 static void worker_request (MonoThreadPoolWorker *worker);
442 mono_threadpool_worker_enqueue (MonoThreadPoolWorker *worker, MonoThreadPoolWorkerCallback callback, gpointer data)
444 work_item_push (worker, callback, data);
446 worker_request (worker);
450 worker_wait_interrupt (gpointer data)
452 MonoThreadPoolWorker *worker;
454 worker = (MonoThreadPoolWorker*) data;
457 mono_coop_mutex_lock (&worker->threads_lock);
458 mono_coop_cond_signal (&worker->parked_threads_cond);
459 mono_coop_mutex_unlock (&worker->threads_lock);
461 mono_refcount_dec (worker);
464 /* return TRUE if timeout, FALSE otherwise (worker unpark or interrupt) */
466 worker_park (MonoThreadPoolWorker *worker)
468 gboolean timeout = FALSE;
470 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] worker parking", mono_native_thread_id_get ());
472 mono_coop_mutex_lock (&worker->threads_lock);
474 if (!mono_runtime_is_shutting_down ()) {
475 static gpointer rand_handle = NULL;
476 MonoInternalThread *thread;
477 gboolean interrupted = FALSE;
478 ThreadPoolWorkerCounter counter;
481 rand_handle = rand_create ();
482 g_assert (rand_handle);
484 thread = mono_thread_internal_current ();
487 COUNTER_ATOMIC (worker, counter, {
488 counter._.working --;
492 worker->parked_threads_count += 1;
494 mono_thread_info_install_interrupt (worker_wait_interrupt, mono_refcount_inc (worker), &interrupted);
496 mono_refcount_dec (worker);
500 if (mono_coop_cond_timedwait (&worker->parked_threads_cond, &worker->threads_lock, rand_next (&rand_handle, 5 * 1000, 60 * 1000)) != 0)
503 mono_thread_info_uninstall_interrupt (&interrupted);
505 mono_refcount_dec (worker);
508 worker->parked_threads_count -= 1;
510 COUNTER_ATOMIC (worker, counter, {
511 counter._.working ++;
516 mono_coop_mutex_unlock (&worker->threads_lock);
518 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] worker unparking, timeout? %s", mono_native_thread_id_get (), timeout ? "yes" : "no");
524 worker_try_unpark (MonoThreadPoolWorker *worker)
526 gboolean res = FALSE;
528 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try unpark worker", mono_native_thread_id_get ());
530 mono_coop_mutex_lock (&worker->threads_lock);
531 if (worker->parked_threads_count > 0) {
532 mono_coop_cond_signal (&worker->parked_threads_cond);
535 mono_coop_mutex_unlock (&worker->threads_lock);
537 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try unpark worker, success? %s", mono_native_thread_id_get (), res ? "yes" : "no");
543 worker_thread (gpointer data)
545 MonoThreadPoolWorker *worker;
547 MonoInternalThread *thread;
548 ThreadPoolWorkerCounter counter;
550 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_THREADPOOL, "[%p] worker starting", mono_native_thread_id_get ());
552 worker = (MonoThreadPoolWorker*) data;
555 COUNTER_ATOMIC (worker, counter, {
556 counter._.starting --;
557 counter._.working ++;
560 thread = mono_thread_internal_current ();
563 mono_coop_mutex_lock (&worker->threads_lock);
564 g_ptr_array_add (worker->threads, thread);
565 mono_coop_mutex_unlock (&worker->threads_lock);
567 mono_thread_set_name_internal (thread, mono_string_new (mono_get_root_domain (), "Threadpool worker"), FALSE, &error);
568 mono_error_assert_ok (&error);
570 while (!mono_runtime_is_shutting_down ()) {
571 ThreadPoolWorkItem work_item;
573 if (mono_thread_interruption_checkpoint ())
576 if (!work_item_try_pop (worker, &work_item)) {
579 timeout = worker_park (worker);
586 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] worker executing %p (%p)",
587 mono_native_thread_id_get (), work_item.callback, work_item.data);
589 work_item.callback (work_item.data);
592 mono_coop_mutex_lock (&worker->threads_lock);
594 COUNTER_ATOMIC (worker, counter, {
595 counter._.working --;
598 g_ptr_array_remove (worker->threads, thread);
600 mono_coop_cond_signal (&worker->threads_exit_cond);
602 mono_coop_mutex_unlock (&worker->threads_lock);
604 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_THREADPOOL, "[%p] worker finishing", mono_native_thread_id_get ());
606 mono_refcount_dec (worker);
612 worker_try_create (MonoThreadPoolWorker *worker)
615 MonoInternalThread *thread;
616 gint64 current_ticks;
618 ThreadPoolWorkerCounter counter;
620 if (mono_runtime_is_shutting_down ())
623 mono_coop_mutex_lock (&worker->worker_creation_lock);
625 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker", mono_native_thread_id_get ());
627 current_ticks = mono_100ns_ticks ();
628 if (0 == current_ticks) {
629 g_warning ("failed to get 100ns ticks");
631 now = current_ticks / (10 * 1000 * 1000);
632 if (worker->worker_creation_current_second != now) {
633 worker->worker_creation_current_second = now;
634 worker->worker_creation_current_count = 0;
636 g_assert (worker->worker_creation_current_count <= WORKER_CREATION_MAX_PER_SEC);
637 if (worker->worker_creation_current_count == WORKER_CREATION_MAX_PER_SEC) {
638 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",
639 mono_native_thread_id_get (), worker->worker_creation_current_count);
640 mono_coop_mutex_unlock (&worker->worker_creation_lock);
646 COUNTER_ATOMIC (worker, counter, {
647 if (counter._.working >= counter._.max_working) {
648 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker, failed: maximum number of working threads reached",
649 mono_native_thread_id_get ());
650 mono_coop_mutex_unlock (&worker->worker_creation_lock);
653 counter._.starting ++;
656 thread = mono_thread_create_internal (mono_get_root_domain (), worker_thread, mono_refcount_inc (worker), TRUE, 0, &error);
658 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));
659 mono_error_cleanup (&error);
661 COUNTER_ATOMIC (worker, counter, {
662 counter._.starting --;
665 mono_coop_mutex_unlock (&worker->worker_creation_lock);
667 mono_refcount_dec (worker);
672 worker->worker_creation_current_count += 1;
674 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker, created %p, now = %d count = %d",
675 mono_native_thread_id_get (), (gpointer) thread->tid, now, worker->worker_creation_current_count);
677 mono_coop_mutex_unlock (&worker->worker_creation_lock);
681 static void monitor_ensure_running (MonoThreadPoolWorker *worker);
684 worker_request (MonoThreadPoolWorker *worker)
688 if (worker->suspended)
691 monitor_ensure_running (worker);
693 if (worker_try_unpark (worker)) {
694 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] request worker, unparked", mono_native_thread_id_get ());
698 if (worker_try_create (worker)) {
699 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] request worker, created", mono_native_thread_id_get ());
703 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] request worker, failed", mono_native_thread_id_get ());
707 monitor_should_keep_running (MonoThreadPoolWorker *worker)
709 static gint64 last_should_keep_running = -1;
711 g_assert (worker->monitor_status == MONITOR_STATUS_WAITING_FOR_REQUEST || worker->monitor_status == MONITOR_STATUS_REQUESTED);
713 if (InterlockedExchange (&worker->monitor_status, MONITOR_STATUS_WAITING_FOR_REQUEST) == MONITOR_STATUS_WAITING_FOR_REQUEST) {
714 gboolean should_keep_running = TRUE, force_should_keep_running = FALSE;
716 if (mono_runtime_is_shutting_down ()) {
717 should_keep_running = FALSE;
719 if (work_item_count (worker) == 0)
720 should_keep_running = FALSE;
722 if (!should_keep_running) {
723 if (last_should_keep_running == -1 || mono_100ns_ticks () - last_should_keep_running < MONITOR_MINIMAL_LIFETIME * 1000 * 10) {
724 should_keep_running = force_should_keep_running = TRUE;
729 if (should_keep_running) {
730 if (last_should_keep_running == -1 || !force_should_keep_running)
731 last_should_keep_running = mono_100ns_ticks ();
733 last_should_keep_running = -1;
734 if (InterlockedCompareExchange (&worker->monitor_status, MONITOR_STATUS_NOT_RUNNING, MONITOR_STATUS_WAITING_FOR_REQUEST) == MONITOR_STATUS_WAITING_FOR_REQUEST)
739 g_assert (worker->monitor_status == MONITOR_STATUS_WAITING_FOR_REQUEST || worker->monitor_status == MONITOR_STATUS_REQUESTED);
745 monitor_sufficient_delay_since_last_dequeue (MonoThreadPoolWorker *worker)
751 if (worker->cpu_usage < CPU_USAGE_LOW) {
752 threshold = MONITOR_INTERVAL;
754 ThreadPoolWorkerCounter counter;
755 counter = COUNTER_READ (worker);
756 threshold = counter._.max_working * MONITOR_INTERVAL * 2;
759 return mono_msec_ticks () >= worker->heuristic_last_dequeue + threshold;
762 static void hill_climbing_force_change (MonoThreadPoolWorker *worker, gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition);
765 monitor_thread (gpointer data)
767 MonoThreadPoolWorker *worker;
768 MonoInternalThread *internal;
771 worker = (MonoThreadPoolWorker*) data;
774 internal = mono_thread_internal_current ();
777 mono_cpu_usage (worker->cpu_usage_state);
779 // printf ("monitor_thread: start\n");
781 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, started", mono_native_thread_id_get ());
784 ThreadPoolWorkerCounter counter;
785 gboolean limit_worker_max_reached;
786 gint32 interval_left = MONITOR_INTERVAL;
787 gint32 awake = 0; /* number of spurious awakes we tolerate before doing a round of rebalancing */
789 g_assert (worker->monitor_status != MONITOR_STATUS_NOT_RUNNING);
791 // counter = COUNTER_READ (worker);
792 // printf ("monitor_thread: starting = %d working = %d parked = %d max_working = %d\n",
793 // counter._.starting, counter._.working, counter._.parked, counter._.max_working);
797 gboolean alerted = FALSE;
799 if (mono_runtime_is_shutting_down ())
802 ts = mono_msec_ticks ();
803 if (mono_thread_info_sleep (interval_left, &alerted) == 0)
805 interval_left -= mono_msec_ticks () - ts;
807 g_assert (!(internal->state & ThreadState_StopRequested));
808 mono_thread_interruption_checkpoint ();
809 } while (interval_left > 0 && ++awake < 10);
811 if (mono_runtime_is_shutting_down ())
814 if (worker->suspended)
817 if (work_item_count (worker) == 0)
820 worker->cpu_usage = mono_cpu_usage (worker->cpu_usage_state);
822 if (!monitor_sufficient_delay_since_last_dequeue (worker))
825 limit_worker_max_reached = FALSE;
827 COUNTER_ATOMIC (worker, counter, {
828 if (counter._.max_working >= worker->limit_worker_max) {
829 limit_worker_max_reached = TRUE;
832 counter._.max_working ++;
835 if (limit_worker_max_reached)
838 hill_climbing_force_change (worker, counter._.max_working, TRANSITION_STARVATION);
840 for (i = 0; i < 5; ++i) {
841 if (mono_runtime_is_shutting_down ())
844 if (worker_try_unpark (worker)) {
845 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, unparked", mono_native_thread_id_get ());
849 if (worker_try_create (worker)) {
850 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, created", mono_native_thread_id_get ());
854 } while (monitor_should_keep_running (worker));
856 // printf ("monitor_thread: stop\n");
858 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, finished", mono_native_thread_id_get ());
864 monitor_ensure_running (MonoThreadPoolWorker *worker)
868 switch (worker->monitor_status) {
869 case MONITOR_STATUS_REQUESTED:
870 // printf ("monitor_thread: requested\n");
872 case MONITOR_STATUS_WAITING_FOR_REQUEST:
873 // printf ("monitor_thread: waiting for request\n");
874 InterlockedCompareExchange (&worker->monitor_status, MONITOR_STATUS_REQUESTED, MONITOR_STATUS_WAITING_FOR_REQUEST);
876 case MONITOR_STATUS_NOT_RUNNING:
877 // printf ("monitor_thread: not running\n");
878 if (mono_runtime_is_shutting_down ())
880 if (InterlockedCompareExchange (&worker->monitor_status, MONITOR_STATUS_REQUESTED, MONITOR_STATUS_NOT_RUNNING) == MONITOR_STATUS_NOT_RUNNING) {
881 // printf ("monitor_thread: creating\n");
882 if (!mono_thread_create_internal (mono_get_root_domain (), monitor_thread, worker, TRUE, SMALL_STACK, &error)) {
883 // printf ("monitor_thread: creating failed\n");
884 worker->monitor_status = MONITOR_STATUS_NOT_RUNNING;
885 mono_error_cleanup (&error);
890 default: g_assert_not_reached ();
896 hill_climbing_change_thread_count (MonoThreadPoolWorker *worker, gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition)
898 ThreadPoolHillClimbing *hc;
902 hc = &worker->heuristic_hill_climbing;
904 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_THREADPOOL, "[%p] hill climbing, change max number of threads %d", mono_native_thread_id_get (), new_thread_count);
906 hc->last_thread_count = new_thread_count;
907 hc->current_sample_interval = rand_next (&hc->random_interval_generator, hc->sample_interval_low, hc->sample_interval_high);
908 hc->elapsed_since_last_change = 0;
909 hc->completions_since_last_change = 0;
913 hill_climbing_force_change (MonoThreadPoolWorker *worker, gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition)
915 ThreadPoolHillClimbing *hc;
919 hc = &worker->heuristic_hill_climbing;
921 if (new_thread_count != hc->last_thread_count) {
922 hc->current_control_setting += new_thread_count - hc->last_thread_count;
923 hill_climbing_change_thread_count (worker, new_thread_count, transition);
927 static double_complex
928 hill_climbing_get_wave_component (MonoThreadPoolWorker *worker, gdouble *samples, guint sample_count, gdouble period)
930 ThreadPoolHillClimbing *hc;
931 gdouble w, cosine, sine, coeff, q0, q1, q2;
935 g_assert (sample_count >= period);
936 g_assert (period >= 2);
938 hc = &worker->heuristic_hill_climbing;
940 w = 2.0 * M_PI / period;
943 coeff = 2.0 * cosine;
946 for (i = 0; i < sample_count; ++i) {
947 q0 = coeff * q1 - q2 + samples [(hc->total_samples - sample_count + i) % hc->samples_to_measure];
952 return mono_double_complex_scalar_div (mono_double_complex_make (q1 - q2 * cosine, (q2 * sine)), ((gdouble)sample_count));
956 hill_climbing_update (MonoThreadPoolWorker *worker, gint16 current_thread_count, guint32 sample_duration, gint32 completions, gint64 *adjustment_interval)
958 ThreadPoolHillClimbing *hc;
959 ThreadPoolHeuristicStateTransition transition;
961 gdouble throughput_error_estimate;
967 gint new_thread_wave_magnitude;
968 gint new_thread_count;
969 double_complex thread_wave_component;
970 double_complex throughput_wave_component;
971 double_complex ratio;
974 g_assert (adjustment_interval);
976 hc = &worker->heuristic_hill_climbing;
978 /* If someone changed the thread count without telling us, update our records accordingly. */
979 if (current_thread_count != hc->last_thread_count)
980 hill_climbing_force_change (worker, current_thread_count, TRANSITION_INITIALIZING);
982 /* Update the cumulative stats for this thread count */
983 hc->elapsed_since_last_change += sample_duration;
984 hc->completions_since_last_change += completions;
986 /* Add in any data we've already collected about this sample */
987 sample_duration += hc->accumulated_sample_duration;
988 completions += hc->accumulated_completion_count;
990 /* We need to make sure we're collecting reasonably accurate data. Since we're just counting the end
991 * of each work item, we are goinng to be missing some data about what really happened during the
992 * sample interval. The count produced by each thread includes an initial work item that may have
993 * started well before the start of the interval, and each thread may have been running some new
994 * work item for some time before the end of the interval, which did not yet get counted. So
995 * our count is going to be off by +/- threadCount workitems.
997 * The exception is that the thread that reported to us last time definitely wasn't running any work
998 * at that time, and the thread that's reporting now definitely isn't running a work item now. So
999 * we really only need to consider threadCount-1 threads.
1001 * Thus the percent error in our count is +/- (threadCount-1)/numCompletions.
1003 * We cannot rely on the frequency-domain analysis we'll be doing later to filter out this error, because
1004 * of the way it accumulates over time. If this sample is off by, say, 33% in the negative direction,
1005 * then the next one likely will be too. The one after that will include the sum of the completions
1006 * we missed in the previous samples, and so will be 33% positive. So every three samples we'll have
1007 * two "low" samples and one "high" sample. This will appear as periodic variation right in the frequency
1008 * range we're targeting, which will not be filtered by the frequency-domain translation. */
1009 if (hc->total_samples > 0 && ((current_thread_count - 1.0) / completions) >= hc->max_sample_error) {
1010 /* Not accurate enough yet. Let's accumulate the data so
1011 * far, and tell the MonoThreadPoolWorker to collect a little more. */
1012 hc->accumulated_sample_duration = sample_duration;
1013 hc->accumulated_completion_count = completions;
1014 *adjustment_interval = 10;
1015 return current_thread_count;
1018 /* We've got enouugh data for our sample; reset our accumulators for next time. */
1019 hc->accumulated_sample_duration = 0;
1020 hc->accumulated_completion_count = 0;
1022 /* Add the current thread count and throughput sample to our history. */
1023 throughput = ((gdouble) completions) / sample_duration;
1025 sample_index = hc->total_samples % hc->samples_to_measure;
1026 hc->samples [sample_index] = throughput;
1027 hc->thread_counts [sample_index] = current_thread_count;
1028 hc->total_samples ++;
1030 /* Set up defaults for our metrics. */
1031 thread_wave_component = mono_double_complex_make(0, 0);
1032 throughput_wave_component = mono_double_complex_make(0, 0);
1033 throughput_error_estimate = 0;
1034 ratio = mono_double_complex_make(0, 0);
1037 transition = TRANSITION_WARMUP;
1039 /* How many samples will we use? It must be at least the three wave periods we're looking for, and it must also
1040 * be a whole multiple of the primary wave's period; otherwise the frequency we're looking for will fall between
1041 * two frequency bands in the Fourier analysis, and we won't be able to measure it accurately. */
1042 sample_count = ((gint) MIN (hc->total_samples - 1, hc->samples_to_measure) / hc->wave_period) * hc->wave_period;
1044 if (sample_count > hc->wave_period) {
1046 gdouble average_throughput;
1047 gdouble average_thread_count;
1048 gdouble sample_sum = 0;
1049 gdouble thread_sum = 0;
1051 /* Average the throughput and thread count samples, so we can scale the wave magnitudes later. */
1052 for (i = 0; i < sample_count; ++i) {
1053 guint j = (hc->total_samples - sample_count + i) % hc->samples_to_measure;
1054 sample_sum += hc->samples [j];
1055 thread_sum += hc->thread_counts [j];
1058 average_throughput = sample_sum / sample_count;
1059 average_thread_count = thread_sum / sample_count;
1061 if (average_throughput > 0 && average_thread_count > 0) {
1062 gdouble noise_for_confidence, adjacent_period_1, adjacent_period_2;
1064 /* Calculate the periods of the adjacent frequency bands we'll be using to
1065 * measure noise levels. We want the two adjacent Fourier frequency bands. */
1066 adjacent_period_1 = sample_count / (((gdouble) sample_count) / ((gdouble) hc->wave_period) + 1);
1067 adjacent_period_2 = sample_count / (((gdouble) sample_count) / ((gdouble) hc->wave_period) - 1);
1069 /* Get the the three different frequency components of the throughput (scaled by average
1070 * throughput). Our "error" estimate (the amount of noise that might be present in the
1071 * frequency band we're really interested in) is the average of the adjacent bands. */
1072 throughput_wave_component = mono_double_complex_scalar_div (hill_climbing_get_wave_component (worker, hc->samples, sample_count, hc->wave_period), average_throughput);
1073 throughput_error_estimate = cabs (mono_double_complex_scalar_div (hill_climbing_get_wave_component (worker, hc->samples, sample_count, adjacent_period_1), average_throughput));
1075 if (adjacent_period_2 <= sample_count) {
1076 throughput_error_estimate = MAX (throughput_error_estimate, cabs (mono_double_complex_scalar_div (hill_climbing_get_wave_component (
1077 worker, hc->samples, sample_count, adjacent_period_2), average_throughput)));
1080 /* Do the same for the thread counts, so we have something to compare to. We don't
1081 * measure thread count noise, because there is none; these are exact measurements. */
1082 thread_wave_component = mono_double_complex_scalar_div (hill_climbing_get_wave_component (worker, hc->thread_counts, sample_count, hc->wave_period), average_thread_count);
1084 /* Update our moving average of the throughput noise. We'll use this
1085 * later as feedback to determine the new size of the thread wave. */
1086 if (hc->average_throughput_noise == 0) {
1087 hc->average_throughput_noise = throughput_error_estimate;
1089 hc->average_throughput_noise = (hc->throughput_error_smoothing_factor * throughput_error_estimate)
1090 + ((1.0 + hc->throughput_error_smoothing_factor) * hc->average_throughput_noise);
1093 if (cabs (thread_wave_component) > 0) {
1094 /* Adjust the throughput wave so it's centered around the target wave,
1095 * and then calculate the adjusted throughput/thread ratio. */
1096 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);
1097 transition = TRANSITION_CLIMBING_MOVE;
1099 ratio = mono_double_complex_make (0, 0);
1100 transition = TRANSITION_STABILIZING;
1103 noise_for_confidence = MAX (hc->average_throughput_noise, throughput_error_estimate);
1104 if (noise_for_confidence > 0) {
1105 confidence = cabs (thread_wave_component) / noise_for_confidence / hc->target_signal_to_noise_ratio;
1107 /* there is no noise! */
1113 /* We use just the real part of the complex ratio we just calculated. If the throughput signal
1114 * is exactly in phase with the thread signal, this will be the same as taking the magnitude of
1115 * the complex move and moving that far up. If they're 180 degrees out of phase, we'll move
1116 * backward (because this indicates that our changes are having the opposite of the intended effect).
1117 * If they're 90 degrees out of phase, we won't move at all, because we can't tell wether we're
1118 * having a negative or positive effect on throughput. */
1119 move = creal (ratio);
1120 move = CLAMP (move, -1.0, 1.0);
1122 /* Apply our confidence multiplier. */
1123 move *= CLAMP (confidence, -1.0, 1.0);
1125 /* Now apply non-linear gain, such that values around zero are attenuated, while higher values
1126 * are enhanced. This allows us to move quickly if we're far away from the target, but more slowly
1127 * if we're getting close, giving us rapid ramp-up without wild oscillations around the target. */
1128 gain = hc->max_change_per_second * sample_duration;
1129 move = pow (fabs (move), hc->gain_exponent) * (move >= 0.0 ? 1 : -1) * gain;
1130 move = MIN (move, hc->max_change_per_sample);
1132 /* If the result was positive, and CPU is > 95%, refuse the move. */
1133 if (move > 0.0 && worker->cpu_usage > CPU_USAGE_HIGH)
1136 /* Apply the move to our control setting. */
1137 hc->current_control_setting += move;
1139 /* Calculate the new thread wave magnitude, which is based on the moving average we've been keeping of the
1140 * throughput error. This average starts at zero, so we'll start with a nice safe little wave at first. */
1141 new_thread_wave_magnitude = (gint)(0.5 + (hc->current_control_setting * hc->average_throughput_noise
1142 * hc->target_signal_to_noise_ratio * hc->thread_magnitude_multiplier * 2.0));
1143 new_thread_wave_magnitude = CLAMP (new_thread_wave_magnitude, 1, hc->max_thread_wave_magnitude);
1145 /* Make sure our control setting is within the MonoThreadPoolWorker's limits. */
1146 hc->current_control_setting = CLAMP (hc->current_control_setting, worker->limit_worker_min, worker->limit_worker_max - new_thread_wave_magnitude);
1148 /* Calculate the new thread count (control setting + square wave). */
1149 new_thread_count = (gint)(hc->current_control_setting + new_thread_wave_magnitude * ((hc->total_samples / (hc->wave_period / 2)) % 2));
1151 /* Make sure the new thread count doesn't exceed the MonoThreadPoolWorker's limits. */
1152 new_thread_count = CLAMP (new_thread_count, worker->limit_worker_min, worker->limit_worker_max);
1154 if (new_thread_count != current_thread_count)
1155 hill_climbing_change_thread_count (worker, new_thread_count, transition);
1157 if (creal (ratio) < 0.0 && new_thread_count == worker->limit_worker_min)
1158 *adjustment_interval = (gint)(0.5 + hc->current_sample_interval * (10.0 * MAX (-1.0 * creal (ratio), 1.0)));
1160 *adjustment_interval = hc->current_sample_interval;
1162 return new_thread_count;
1166 heuristic_should_adjust (MonoThreadPoolWorker *worker)
1168 if (worker->heuristic_last_dequeue > worker->heuristic_last_adjustment + worker->heuristic_adjustment_interval) {
1169 ThreadPoolWorkerCounter counter;
1170 counter = COUNTER_READ (worker);
1171 if (counter._.working <= counter._.max_working)
1179 heuristic_adjust (MonoThreadPoolWorker *worker)
1181 if (mono_coop_mutex_trylock (&worker->heuristic_lock) == 0) {
1182 gint32 completions = InterlockedExchange (&worker->heuristic_completions, 0);
1183 gint64 sample_end = mono_msec_ticks ();
1184 gint64 sample_duration = sample_end - worker->heuristic_sample_start;
1186 if (sample_duration >= worker->heuristic_adjustment_interval / 2) {
1187 ThreadPoolWorkerCounter counter;
1188 gint16 new_thread_count;
1190 counter = COUNTER_READ (worker);
1191 new_thread_count = hill_climbing_update (worker, counter._.max_working, sample_duration, completions, &worker->heuristic_adjustment_interval);
1193 COUNTER_ATOMIC (worker, counter, {
1194 counter._.max_working = new_thread_count;
1197 if (new_thread_count > counter._.max_working)
1198 worker_request (worker);
1200 worker->heuristic_sample_start = sample_end;
1201 worker->heuristic_last_adjustment = mono_msec_ticks ();
1204 mono_coop_mutex_unlock (&worker->heuristic_lock);
1209 heuristic_notify_work_completed (MonoThreadPoolWorker *worker)
1213 InterlockedIncrement (&worker->heuristic_completions);
1214 worker->heuristic_last_dequeue = mono_msec_ticks ();
1216 if (heuristic_should_adjust (worker))
1217 heuristic_adjust (worker);
1221 mono_threadpool_worker_notify_completed (MonoThreadPoolWorker *worker)
1223 ThreadPoolWorkerCounter counter;
1225 heuristic_notify_work_completed (worker);
1227 counter = COUNTER_READ (worker);
1228 return counter._.working <= counter._.max_working;
1232 mono_threadpool_worker_get_min (MonoThreadPoolWorker *worker)
1234 return worker->limit_worker_min;
1238 mono_threadpool_worker_set_min (MonoThreadPoolWorker *worker, gint32 value)
1240 if (value <= 0 || value > worker->limit_worker_max)
1243 worker->limit_worker_min = value;
1248 mono_threadpool_worker_get_max (MonoThreadPoolWorker *worker)
1250 return worker->limit_worker_max;
1254 mono_threadpool_worker_set_max (MonoThreadPoolWorker *worker, gint32 value)
1256 gint32 cpu_count = mono_cpu_count ();
1258 if (value < worker->limit_worker_min || value < cpu_count)
1261 worker->limit_worker_max = value;
1266 mono_threadpool_worker_set_suspended (MonoThreadPoolWorker *worker, gboolean suspended)
1268 worker->suspended = suspended;
1270 worker_request (worker);