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>
36 #include <mono/utils/w32api.h>
38 #define CPU_USAGE_LOW 80
39 #define CPU_USAGE_HIGH 95
41 #define MONITOR_INTERVAL 500 // ms
42 #define MONITOR_MINIMAL_LIFETIME 60 * 1000 // ms
44 #define WORKER_CREATION_MAX_PER_SEC 10
46 /* The exponent to apply to the gain. 1.0 means to use linear gain,
47 * higher values will enhance large moves and damp small ones.
49 #define HILL_CLIMBING_GAIN_EXPONENT 2.0
51 /* The 'cost' of a thread. 0 means drive for increased throughput regardless
52 * of thread count, higher values bias more against higher thread counts.
54 #define HILL_CLIMBING_BIAS 0.15
56 #define HILL_CLIMBING_WAVE_PERIOD 4
57 #define HILL_CLIMBING_MAX_WAVE_MAGNITUDE 20
58 #define HILL_CLIMBING_WAVE_MAGNITUDE_MULTIPLIER 1.0
59 #define HILL_CLIMBING_WAVE_HISTORY_SIZE 8
60 #define HILL_CLIMBING_TARGET_SIGNAL_TO_NOISE_RATIO 3.0
61 #define HILL_CLIMBING_MAX_CHANGE_PER_SECOND 4
62 #define HILL_CLIMBING_MAX_CHANGE_PER_SAMPLE 20
63 #define HILL_CLIMBING_SAMPLE_INTERVAL_LOW 10
64 #define HILL_CLIMBING_SAMPLE_INTERVAL_HIGH 200
65 #define HILL_CLIMBING_ERROR_SMOOTHING_FACTOR 0.01
66 #define HILL_CLIMBING_MAX_SAMPLE_ERROR_PERCENT 0.15
70 TRANSITION_INITIALIZING,
71 TRANSITION_RANDOM_MOVE,
72 TRANSITION_CLIMBING_MOVE,
73 TRANSITION_CHANGE_POINT,
74 TRANSITION_STABILIZING,
75 TRANSITION_STARVATION,
76 TRANSITION_THREAD_TIMED_OUT,
78 } ThreadPoolHeuristicStateTransition;
82 gint32 samples_to_measure;
83 gdouble target_throughput_ratio;
84 gdouble target_signal_to_noise_ratio;
85 gdouble max_change_per_second;
86 gdouble max_change_per_sample;
87 gint32 max_thread_wave_magnitude;
88 gint32 sample_interval_low;
89 gdouble thread_magnitude_multiplier;
90 gint32 sample_interval_high;
91 gdouble throughput_error_smoothing_factor;
92 gdouble gain_exponent;
93 gdouble max_sample_error;
95 gdouble current_control_setting;
97 gint16 last_thread_count;
98 gdouble elapsed_since_last_change;
99 gdouble completions_since_last_change;
101 gdouble average_throughput_noise;
104 gdouble *thread_counts;
106 guint32 current_sample_interval;
107 gpointer random_interval_generator;
109 gint32 accumulated_completion_count;
110 gdouble accumulated_sample_duration;
111 } ThreadPoolHillClimbing;
114 MonoThreadPoolWorkerCallback callback;
116 } ThreadPoolWorkItem;
120 gint16 max_working; /* determined by heuristic */
121 gint16 starting; /* starting, but not yet in worker_thread */
122 gint16 working; /* executing worker_thread */
123 gint16 parked; /* parked */
126 } ThreadPoolWorkerCounter;
128 typedef MonoInternalThread ThreadPoolWorkerThread;
130 struct MonoThreadPoolWorker {
133 ThreadPoolWorkerCounter counters;
135 GPtrArray *threads; // ThreadPoolWorkerThread* []
136 MonoCoopMutex threads_lock; /* protect access to working_threads and parked_threads */
137 gint32 parked_threads_count;
138 MonoCoopCond parked_threads_cond;
139 MonoCoopCond threads_exit_cond;
141 ThreadPoolWorkItem *work_items; // ThreadPoolWorkItem []
142 gint32 work_items_count;
143 gint32 work_items_size;
144 MonoCoopMutex work_items_lock;
146 guint32 worker_creation_current_second;
147 guint32 worker_creation_current_count;
148 MonoCoopMutex worker_creation_lock;
150 gint32 heuristic_completions;
151 gint64 heuristic_sample_start;
152 gint64 heuristic_last_dequeue; // ms
153 gint64 heuristic_last_adjustment; // ms
154 gint64 heuristic_adjustment_interval; // ms
155 ThreadPoolHillClimbing heuristic_hill_climbing;
156 MonoCoopMutex heuristic_lock;
158 gint32 limit_worker_min;
159 gint32 limit_worker_max;
161 MonoCpuUsageState *cpu_usage_state;
164 /* suspended by the debugger */
167 gint32 monitor_status;
171 MONITOR_STATUS_REQUESTED,
172 MONITOR_STATUS_WAITING_FOR_REQUEST,
173 MONITOR_STATUS_NOT_RUNNING,
176 #define COUNTER_CHECK(counter) \
178 g_assert (counter._.max_working > 0); \
179 g_assert (counter._.starting >= 0); \
180 g_assert (counter._.working >= 0); \
183 #define COUNTER_ATOMIC(worker,var,block) \
185 ThreadPoolWorkerCounter __old; \
188 __old = COUNTER_READ (worker); \
191 COUNTER_CHECK (var); \
192 } while (InterlockedCompareExchange64 (&worker->counters.as_gint64, (var).as_gint64, __old.as_gint64) != __old.as_gint64); \
195 static inline ThreadPoolWorkerCounter
196 COUNTER_READ (MonoThreadPoolWorker *worker)
198 ThreadPoolWorkerCounter counter;
199 counter.as_gint64 = InterlockedRead64 (&worker->counters.as_gint64);
207 return mono_rand_init (NULL, 0);
211 rand_next (gpointer *handle, guint32 min, guint32 max)
215 mono_rand_try_get_uint32 (handle, &val, min, max, &error);
216 // FIXME handle error
217 mono_error_assert_ok (&error);
222 destroy (gpointer data)
224 MonoThreadPoolWorker *worker;
226 worker = (MonoThreadPoolWorker*) data;
229 // FIXME destroy everything
235 mono_threadpool_worker_init (MonoThreadPoolWorker **worker)
237 MonoThreadPoolWorker *wk;
238 ThreadPoolHillClimbing *hc;
239 const char *threads_per_cpu_env;
240 gint threads_per_cpu;
245 wk = *worker = g_new0 (MonoThreadPoolWorker, 1);
247 mono_refcount_init (wk, destroy);
249 wk->threads = g_ptr_array_new ();
250 mono_coop_mutex_init (&wk->threads_lock);
251 wk->parked_threads_count = 0;
252 mono_coop_cond_init (&wk->parked_threads_cond);
253 mono_coop_cond_init (&wk->threads_exit_cond);
255 /* wk->work_items_size is inited to 0 */
256 mono_coop_mutex_init (&wk->work_items_lock);
258 wk->worker_creation_current_second = -1;
259 mono_coop_mutex_init (&wk->worker_creation_lock);
261 wk->heuristic_adjustment_interval = 10;
262 mono_coop_mutex_init (&wk->heuristic_lock);
266 hc = &wk->heuristic_hill_climbing;
268 hc->wave_period = HILL_CLIMBING_WAVE_PERIOD;
269 hc->max_thread_wave_magnitude = HILL_CLIMBING_MAX_WAVE_MAGNITUDE;
270 hc->thread_magnitude_multiplier = (gdouble) HILL_CLIMBING_WAVE_MAGNITUDE_MULTIPLIER;
271 hc->samples_to_measure = hc->wave_period * HILL_CLIMBING_WAVE_HISTORY_SIZE;
272 hc->target_throughput_ratio = (gdouble) HILL_CLIMBING_BIAS;
273 hc->target_signal_to_noise_ratio = (gdouble) HILL_CLIMBING_TARGET_SIGNAL_TO_NOISE_RATIO;
274 hc->max_change_per_second = (gdouble) HILL_CLIMBING_MAX_CHANGE_PER_SECOND;
275 hc->max_change_per_sample = (gdouble) HILL_CLIMBING_MAX_CHANGE_PER_SAMPLE;
276 hc->sample_interval_low = HILL_CLIMBING_SAMPLE_INTERVAL_LOW;
277 hc->sample_interval_high = HILL_CLIMBING_SAMPLE_INTERVAL_HIGH;
278 hc->throughput_error_smoothing_factor = (gdouble) HILL_CLIMBING_ERROR_SMOOTHING_FACTOR;
279 hc->gain_exponent = (gdouble) HILL_CLIMBING_GAIN_EXPONENT;
280 hc->max_sample_error = (gdouble) HILL_CLIMBING_MAX_SAMPLE_ERROR_PERCENT;
281 hc->current_control_setting = 0;
282 hc->total_samples = 0;
283 hc->last_thread_count = 0;
284 hc->average_throughput_noise = 0;
285 hc->elapsed_since_last_change = 0;
286 hc->accumulated_completion_count = 0;
287 hc->accumulated_sample_duration = 0;
288 hc->samples = g_new0 (gdouble, hc->samples_to_measure);
289 hc->thread_counts = g_new0 (gdouble, hc->samples_to_measure);
290 hc->random_interval_generator = rand_create ();
291 hc->current_sample_interval = rand_next (&hc->random_interval_generator, hc->sample_interval_low, hc->sample_interval_high);
293 if (!(threads_per_cpu_env = g_getenv ("MONO_THREADS_PER_CPU")))
296 threads_per_cpu = CLAMP (atoi (threads_per_cpu_env), 1, 50);
298 threads_count = mono_cpu_count () * threads_per_cpu;
300 wk->limit_worker_min = threads_count;
302 #if defined (PLATFORM_ANDROID) || defined (HOST_IOS)
303 wk->limit_worker_max = CLAMP (threads_count * 100, MIN (threads_count, 200), MAX (threads_count, 200));
305 wk->limit_worker_max = threads_count * 100;
308 wk->counters._.max_working = wk->limit_worker_min;
310 wk->cpu_usage_state = g_new0 (MonoCpuUsageState, 1);
312 wk->suspended = FALSE;
314 wk->monitor_status = MONITOR_STATUS_NOT_RUNNING;
318 mono_threadpool_worker_cleanup (MonoThreadPoolWorker *worker)
320 MonoInternalThread *current;
322 /* we make the assumption along the code that we are
323 * cleaning up only if the runtime is shutting down */
324 g_assert (mono_runtime_is_shutting_down ());
326 current = mono_thread_internal_current ();
328 while (worker->monitor_status != MONITOR_STATUS_NOT_RUNNING)
329 mono_thread_info_sleep (1, NULL);
331 mono_coop_mutex_lock (&worker->threads_lock);
333 /* unpark all worker->parked_threads */
334 mono_coop_cond_broadcast (&worker->parked_threads_cond);
338 ThreadPoolWorkerCounter counter;
340 counter = COUNTER_READ (worker);
341 if (counter._.starting + counter._.working + counter._.parked == 0)
344 if (counter._.starting + counter._.working + counter._.parked == 1) {
345 if (worker->threads->len == 1 && g_ptr_array_index (worker->threads, 0) == current) {
346 /* We are waiting on ourselves */
351 mono_coop_cond_wait (&worker->threads_exit_cond, &worker->threads_lock);
355 mono_coop_mutex_unlock (&worker->threads_lock);
357 mono_refcount_dec (worker);
361 work_item_lock (MonoThreadPoolWorker *worker)
363 mono_coop_mutex_lock (&worker->work_items_lock);
367 work_item_unlock (MonoThreadPoolWorker *worker)
369 mono_coop_mutex_unlock (&worker->work_items_lock);
373 work_item_push (MonoThreadPoolWorker *worker, MonoThreadPoolWorkerCallback callback, gpointer data)
375 ThreadPoolWorkItem work_item;
380 work_item.callback = callback;
381 work_item.data = data;
383 work_item_lock (worker);
385 g_assert (worker->work_items_count <= worker->work_items_size);
387 if (G_UNLIKELY (worker->work_items_count == worker->work_items_size)) {
388 worker->work_items_size += 64;
389 worker->work_items = g_renew (ThreadPoolWorkItem, worker->work_items, worker->work_items_size);
392 g_assert (worker->work_items);
394 worker->work_items [worker->work_items_count ++] = work_item;
396 // printf ("[push] worker->work_items = %p, worker->work_items_count = %d, worker->work_items_size = %d\n",
397 // worker->work_items, worker->work_items_count, worker->work_items_size);
399 work_item_unlock (worker);
403 work_item_try_pop (MonoThreadPoolWorker *worker, ThreadPoolWorkItem *work_item)
406 g_assert (work_item);
408 work_item_lock (worker);
410 // printf ("[pop] worker->work_items = %p, worker->work_items_count = %d, worker->work_items_size = %d\n",
411 // worker->work_items, worker->work_items_count, worker->work_items_size);
413 if (worker->work_items_count == 0) {
414 work_item_unlock (worker);
418 *work_item = worker->work_items [-- worker->work_items_count];
420 if (G_UNLIKELY (worker->work_items_count >= 64 * 3 && worker->work_items_count < worker->work_items_size / 2)) {
421 worker->work_items_size -= 64;
422 worker->work_items = g_renew (ThreadPoolWorkItem, worker->work_items, worker->work_items_size);
425 work_item_unlock (worker);
431 work_item_count (MonoThreadPoolWorker *worker)
435 work_item_lock (worker);
436 count = worker->work_items_count;
437 work_item_unlock (worker);
442 static void worker_request (MonoThreadPoolWorker *worker);
445 mono_threadpool_worker_enqueue (MonoThreadPoolWorker *worker, MonoThreadPoolWorkerCallback callback, gpointer data)
447 work_item_push (worker, callback, data);
449 worker_request (worker);
453 worker_wait_interrupt (gpointer data)
455 MonoThreadPoolWorker *worker;
457 worker = (MonoThreadPoolWorker*) data;
460 mono_coop_mutex_lock (&worker->threads_lock);
461 mono_coop_cond_signal (&worker->parked_threads_cond);
462 mono_coop_mutex_unlock (&worker->threads_lock);
464 mono_refcount_dec (worker);
467 /* return TRUE if timeout, FALSE otherwise (worker unpark or interrupt) */
469 worker_park (MonoThreadPoolWorker *worker)
471 gboolean timeout = FALSE;
473 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] worker parking", mono_native_thread_id_get ());
475 mono_coop_mutex_lock (&worker->threads_lock);
477 if (!mono_runtime_is_shutting_down ()) {
478 static gpointer rand_handle = NULL;
479 MonoInternalThread *thread;
480 gboolean interrupted = FALSE;
481 ThreadPoolWorkerCounter counter;
484 rand_handle = rand_create ();
485 g_assert (rand_handle);
487 thread = mono_thread_internal_current ();
490 COUNTER_ATOMIC (worker, counter, {
491 counter._.working --;
495 worker->parked_threads_count += 1;
497 mono_thread_info_install_interrupt (worker_wait_interrupt, mono_refcount_inc (worker), &interrupted);
499 mono_refcount_dec (worker);
503 if (mono_coop_cond_timedwait (&worker->parked_threads_cond, &worker->threads_lock, rand_next (&rand_handle, 5 * 1000, 60 * 1000)) != 0)
506 mono_thread_info_uninstall_interrupt (&interrupted);
508 mono_refcount_dec (worker);
511 worker->parked_threads_count -= 1;
513 COUNTER_ATOMIC (worker, counter, {
514 counter._.working ++;
519 mono_coop_mutex_unlock (&worker->threads_lock);
521 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] worker unparking, timeout? %s", mono_native_thread_id_get (), timeout ? "yes" : "no");
527 worker_try_unpark (MonoThreadPoolWorker *worker)
529 gboolean res = FALSE;
531 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try unpark worker", mono_native_thread_id_get ());
533 mono_coop_mutex_lock (&worker->threads_lock);
534 if (worker->parked_threads_count > 0) {
535 mono_coop_cond_signal (&worker->parked_threads_cond);
538 mono_coop_mutex_unlock (&worker->threads_lock);
540 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try unpark worker, success? %s", mono_native_thread_id_get (), res ? "yes" : "no");
546 worker_thread (gpointer data)
548 MonoThreadPoolWorker *worker;
549 MonoInternalThread *thread;
550 ThreadPoolWorkerCounter counter;
552 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_THREADPOOL, "[%p] worker starting", mono_native_thread_id_get ());
554 worker = (MonoThreadPoolWorker*) data;
557 COUNTER_ATOMIC (worker, counter, {
558 counter._.starting --;
559 counter._.working ++;
562 thread = mono_thread_internal_current ();
565 mono_coop_mutex_lock (&worker->threads_lock);
566 g_ptr_array_add (worker->threads, thread);
567 mono_coop_mutex_unlock (&worker->threads_lock);
569 while (!mono_runtime_is_shutting_down ()) {
570 ThreadPoolWorkItem work_item;
572 if (mono_thread_interruption_checkpoint ())
575 if (!work_item_try_pop (worker, &work_item)) {
578 timeout = worker_park (worker);
585 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] worker executing %p (%p)",
586 mono_native_thread_id_get (), work_item.callback, work_item.data);
588 work_item.callback (work_item.data);
591 mono_coop_mutex_lock (&worker->threads_lock);
593 COUNTER_ATOMIC (worker, counter, {
594 counter._.working --;
597 g_ptr_array_remove (worker->threads, thread);
599 mono_coop_cond_signal (&worker->threads_exit_cond);
601 mono_coop_mutex_unlock (&worker->threads_lock);
603 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_THREADPOOL, "[%p] worker finishing", mono_native_thread_id_get ());
605 mono_refcount_dec (worker);
611 worker_try_create (MonoThreadPoolWorker *worker)
614 MonoInternalThread *thread;
615 gint64 current_ticks;
617 ThreadPoolWorkerCounter counter;
619 if (mono_runtime_is_shutting_down ())
622 mono_coop_mutex_lock (&worker->worker_creation_lock);
624 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker", mono_native_thread_id_get ());
626 current_ticks = mono_100ns_ticks ();
627 if (0 == current_ticks) {
628 g_warning ("failed to get 100ns ticks");
630 now = current_ticks / (10 * 1000 * 1000);
631 if (worker->worker_creation_current_second != now) {
632 worker->worker_creation_current_second = now;
633 worker->worker_creation_current_count = 0;
635 g_assert (worker->worker_creation_current_count <= WORKER_CREATION_MAX_PER_SEC);
636 if (worker->worker_creation_current_count == WORKER_CREATION_MAX_PER_SEC) {
637 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",
638 mono_native_thread_id_get (), worker->worker_creation_current_count);
639 mono_coop_mutex_unlock (&worker->worker_creation_lock);
645 COUNTER_ATOMIC (worker, counter, {
646 if (counter._.working >= counter._.max_working) {
647 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker, failed: maximum number of working threads reached",
648 mono_native_thread_id_get ());
649 mono_coop_mutex_unlock (&worker->worker_creation_lock);
652 counter._.starting ++;
655 thread = mono_thread_create_internal (mono_get_root_domain (), worker_thread, mono_refcount_inc (worker), TRUE, 0, &error);
657 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));
658 mono_error_cleanup (&error);
660 COUNTER_ATOMIC (worker, counter, {
661 counter._.starting --;
664 mono_coop_mutex_unlock (&worker->worker_creation_lock);
666 mono_refcount_dec (worker);
671 worker->worker_creation_current_count += 1;
673 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker, created %p, now = %d count = %d",
674 mono_native_thread_id_get (), (gpointer) thread->tid, now, worker->worker_creation_current_count);
676 mono_coop_mutex_unlock (&worker->worker_creation_lock);
680 static void monitor_ensure_running (MonoThreadPoolWorker *worker);
683 worker_request (MonoThreadPoolWorker *worker)
687 if (worker->suspended)
690 monitor_ensure_running (worker);
692 if (worker_try_unpark (worker)) {
693 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] request worker, unparked", mono_native_thread_id_get ());
697 if (worker_try_create (worker)) {
698 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] request worker, created", mono_native_thread_id_get ());
702 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] request worker, failed", mono_native_thread_id_get ());
706 monitor_should_keep_running (MonoThreadPoolWorker *worker)
708 static gint64 last_should_keep_running = -1;
710 g_assert (worker->monitor_status == MONITOR_STATUS_WAITING_FOR_REQUEST || worker->monitor_status == MONITOR_STATUS_REQUESTED);
712 if (InterlockedExchange (&worker->monitor_status, MONITOR_STATUS_WAITING_FOR_REQUEST) == MONITOR_STATUS_WAITING_FOR_REQUEST) {
713 gboolean should_keep_running = TRUE, force_should_keep_running = FALSE;
715 if (mono_runtime_is_shutting_down ()) {
716 should_keep_running = FALSE;
718 if (work_item_count (worker) == 0)
719 should_keep_running = FALSE;
721 if (!should_keep_running) {
722 if (last_should_keep_running == -1 || mono_100ns_ticks () - last_should_keep_running < MONITOR_MINIMAL_LIFETIME * 1000 * 10) {
723 should_keep_running = force_should_keep_running = TRUE;
728 if (should_keep_running) {
729 if (last_should_keep_running == -1 || !force_should_keep_running)
730 last_should_keep_running = mono_100ns_ticks ();
732 last_should_keep_running = -1;
733 if (InterlockedCompareExchange (&worker->monitor_status, MONITOR_STATUS_NOT_RUNNING, MONITOR_STATUS_WAITING_FOR_REQUEST) == MONITOR_STATUS_WAITING_FOR_REQUEST)
738 g_assert (worker->monitor_status == MONITOR_STATUS_WAITING_FOR_REQUEST || worker->monitor_status == MONITOR_STATUS_REQUESTED);
744 monitor_sufficient_delay_since_last_dequeue (MonoThreadPoolWorker *worker)
750 if (worker->cpu_usage < CPU_USAGE_LOW) {
751 threshold = MONITOR_INTERVAL;
753 ThreadPoolWorkerCounter counter;
754 counter = COUNTER_READ (worker);
755 threshold = counter._.max_working * MONITOR_INTERVAL * 2;
758 return mono_msec_ticks () >= worker->heuristic_last_dequeue + threshold;
761 static void hill_climbing_force_change (MonoThreadPoolWorker *worker, gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition);
764 monitor_thread (gpointer data)
766 MonoThreadPoolWorker *worker;
767 MonoInternalThread *internal;
770 worker = (MonoThreadPoolWorker*) data;
773 internal = mono_thread_internal_current ();
776 mono_cpu_usage (worker->cpu_usage_state);
778 // printf ("monitor_thread: start\n");
780 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, started", mono_native_thread_id_get ());
783 ThreadPoolWorkerCounter counter;
784 gboolean limit_worker_max_reached;
785 gint32 interval_left = MONITOR_INTERVAL;
786 gint32 awake = 0; /* number of spurious awakes we tolerate before doing a round of rebalancing */
788 g_assert (worker->monitor_status != MONITOR_STATUS_NOT_RUNNING);
790 // counter = COUNTER_READ (worker);
791 // printf ("monitor_thread: starting = %d working = %d parked = %d max_working = %d\n",
792 // counter._.starting, counter._.working, counter._.parked, counter._.max_working);
796 gboolean alerted = FALSE;
798 if (mono_runtime_is_shutting_down ())
801 ts = mono_msec_ticks ();
802 if (mono_thread_info_sleep (interval_left, &alerted) == 0)
804 interval_left -= mono_msec_ticks () - ts;
806 g_assert (!(internal->state & ThreadState_StopRequested));
807 mono_thread_interruption_checkpoint ();
808 } while (interval_left > 0 && ++awake < 10);
810 if (mono_runtime_is_shutting_down ())
813 if (worker->suspended)
816 if (work_item_count (worker) == 0)
819 worker->cpu_usage = mono_cpu_usage (worker->cpu_usage_state);
821 if (!monitor_sufficient_delay_since_last_dequeue (worker))
824 limit_worker_max_reached = FALSE;
826 COUNTER_ATOMIC (worker, counter, {
827 if (counter._.max_working >= worker->limit_worker_max) {
828 limit_worker_max_reached = TRUE;
831 counter._.max_working ++;
834 if (limit_worker_max_reached)
837 hill_climbing_force_change (worker, counter._.max_working, TRANSITION_STARVATION);
839 for (i = 0; i < 5; ++i) {
840 if (mono_runtime_is_shutting_down ())
843 if (worker_try_unpark (worker)) {
844 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, unparked", mono_native_thread_id_get ());
848 if (worker_try_create (worker)) {
849 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, created", mono_native_thread_id_get ());
853 } while (monitor_should_keep_running (worker));
855 // printf ("monitor_thread: stop\n");
857 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, finished", mono_native_thread_id_get ());
863 monitor_ensure_running (MonoThreadPoolWorker *worker)
867 switch (worker->monitor_status) {
868 case MONITOR_STATUS_REQUESTED:
869 // printf ("monitor_thread: requested\n");
871 case MONITOR_STATUS_WAITING_FOR_REQUEST:
872 // printf ("monitor_thread: waiting for request\n");
873 InterlockedCompareExchange (&worker->monitor_status, MONITOR_STATUS_REQUESTED, MONITOR_STATUS_WAITING_FOR_REQUEST);
875 case MONITOR_STATUS_NOT_RUNNING:
876 // printf ("monitor_thread: not running\n");
877 if (mono_runtime_is_shutting_down ())
879 if (InterlockedCompareExchange (&worker->monitor_status, MONITOR_STATUS_REQUESTED, MONITOR_STATUS_NOT_RUNNING) == MONITOR_STATUS_NOT_RUNNING) {
880 // printf ("monitor_thread: creating\n");
881 if (!mono_thread_create_internal (mono_get_root_domain (), monitor_thread, worker, TRUE, SMALL_STACK, &error)) {
882 // printf ("monitor_thread: creating failed\n");
883 worker->monitor_status = MONITOR_STATUS_NOT_RUNNING;
884 mono_error_cleanup (&error);
889 default: g_assert_not_reached ();
895 hill_climbing_change_thread_count (MonoThreadPoolWorker *worker, gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition)
897 ThreadPoolHillClimbing *hc;
901 hc = &worker->heuristic_hill_climbing;
903 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);
905 hc->last_thread_count = new_thread_count;
906 hc->current_sample_interval = rand_next (&hc->random_interval_generator, hc->sample_interval_low, hc->sample_interval_high);
907 hc->elapsed_since_last_change = 0;
908 hc->completions_since_last_change = 0;
912 hill_climbing_force_change (MonoThreadPoolWorker *worker, gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition)
914 ThreadPoolHillClimbing *hc;
918 hc = &worker->heuristic_hill_climbing;
920 if (new_thread_count != hc->last_thread_count) {
921 hc->current_control_setting += new_thread_count - hc->last_thread_count;
922 hill_climbing_change_thread_count (worker, new_thread_count, transition);
926 static double_complex
927 hill_climbing_get_wave_component (MonoThreadPoolWorker *worker, gdouble *samples, guint sample_count, gdouble period)
929 ThreadPoolHillClimbing *hc;
930 gdouble w, cosine, sine, coeff, q0, q1, q2;
934 g_assert (sample_count >= period);
935 g_assert (period >= 2);
937 hc = &worker->heuristic_hill_climbing;
939 w = 2.0 * M_PI / period;
942 coeff = 2.0 * cosine;
945 for (i = 0; i < sample_count; ++i) {
946 q0 = coeff * q1 - q2 + samples [(hc->total_samples - sample_count + i) % hc->samples_to_measure];
951 return mono_double_complex_scalar_div (mono_double_complex_make (q1 - q2 * cosine, (q2 * sine)), ((gdouble)sample_count));
955 hill_climbing_update (MonoThreadPoolWorker *worker, gint16 current_thread_count, guint32 sample_duration, gint32 completions, gint64 *adjustment_interval)
957 ThreadPoolHillClimbing *hc;
958 ThreadPoolHeuristicStateTransition transition;
960 gdouble throughput_error_estimate;
966 gint new_thread_wave_magnitude;
967 gint new_thread_count;
968 double_complex thread_wave_component;
969 double_complex throughput_wave_component;
970 double_complex ratio;
973 g_assert (adjustment_interval);
975 hc = &worker->heuristic_hill_climbing;
977 /* If someone changed the thread count without telling us, update our records accordingly. */
978 if (current_thread_count != hc->last_thread_count)
979 hill_climbing_force_change (worker, current_thread_count, TRANSITION_INITIALIZING);
981 /* Update the cumulative stats for this thread count */
982 hc->elapsed_since_last_change += sample_duration;
983 hc->completions_since_last_change += completions;
985 /* Add in any data we've already collected about this sample */
986 sample_duration += hc->accumulated_sample_duration;
987 completions += hc->accumulated_completion_count;
989 /* We need to make sure we're collecting reasonably accurate data. Since we're just counting the end
990 * of each work item, we are goinng to be missing some data about what really happened during the
991 * sample interval. The count produced by each thread includes an initial work item that may have
992 * started well before the start of the interval, and each thread may have been running some new
993 * work item for some time before the end of the interval, which did not yet get counted. So
994 * our count is going to be off by +/- threadCount workitems.
996 * The exception is that the thread that reported to us last time definitely wasn't running any work
997 * at that time, and the thread that's reporting now definitely isn't running a work item now. So
998 * we really only need to consider threadCount-1 threads.
1000 * Thus the percent error in our count is +/- (threadCount-1)/numCompletions.
1002 * We cannot rely on the frequency-domain analysis we'll be doing later to filter out this error, because
1003 * of the way it accumulates over time. If this sample is off by, say, 33% in the negative direction,
1004 * then the next one likely will be too. The one after that will include the sum of the completions
1005 * we missed in the previous samples, and so will be 33% positive. So every three samples we'll have
1006 * two "low" samples and one "high" sample. This will appear as periodic variation right in the frequency
1007 * range we're targeting, which will not be filtered by the frequency-domain translation. */
1008 if (hc->total_samples > 0 && ((current_thread_count - 1.0) / completions) >= hc->max_sample_error) {
1009 /* Not accurate enough yet. Let's accumulate the data so
1010 * far, and tell the MonoThreadPoolWorker to collect a little more. */
1011 hc->accumulated_sample_duration = sample_duration;
1012 hc->accumulated_completion_count = completions;
1013 *adjustment_interval = 10;
1014 return current_thread_count;
1017 /* We've got enouugh data for our sample; reset our accumulators for next time. */
1018 hc->accumulated_sample_duration = 0;
1019 hc->accumulated_completion_count = 0;
1021 /* Add the current thread count and throughput sample to our history. */
1022 throughput = ((gdouble) completions) / sample_duration;
1024 sample_index = hc->total_samples % hc->samples_to_measure;
1025 hc->samples [sample_index] = throughput;
1026 hc->thread_counts [sample_index] = current_thread_count;
1027 hc->total_samples ++;
1029 /* Set up defaults for our metrics. */
1030 thread_wave_component = mono_double_complex_make(0, 0);
1031 throughput_wave_component = mono_double_complex_make(0, 0);
1032 throughput_error_estimate = 0;
1033 ratio = mono_double_complex_make(0, 0);
1036 transition = TRANSITION_WARMUP;
1038 /* How many samples will we use? It must be at least the three wave periods we're looking for, and it must also
1039 * be a whole multiple of the primary wave's period; otherwise the frequency we're looking for will fall between
1040 * two frequency bands in the Fourier analysis, and we won't be able to measure it accurately. */
1041 sample_count = ((gint) MIN (hc->total_samples - 1, hc->samples_to_measure) / hc->wave_period) * hc->wave_period;
1043 if (sample_count > hc->wave_period) {
1045 gdouble average_throughput;
1046 gdouble average_thread_count;
1047 gdouble sample_sum = 0;
1048 gdouble thread_sum = 0;
1050 /* Average the throughput and thread count samples, so we can scale the wave magnitudes later. */
1051 for (i = 0; i < sample_count; ++i) {
1052 guint j = (hc->total_samples - sample_count + i) % hc->samples_to_measure;
1053 sample_sum += hc->samples [j];
1054 thread_sum += hc->thread_counts [j];
1057 average_throughput = sample_sum / sample_count;
1058 average_thread_count = thread_sum / sample_count;
1060 if (average_throughput > 0 && average_thread_count > 0) {
1061 gdouble noise_for_confidence, adjacent_period_1, adjacent_period_2;
1063 /* Calculate the periods of the adjacent frequency bands we'll be using to
1064 * measure noise levels. We want the two adjacent Fourier frequency bands. */
1065 adjacent_period_1 = sample_count / (((gdouble) sample_count) / ((gdouble) hc->wave_period) + 1);
1066 adjacent_period_2 = sample_count / (((gdouble) sample_count) / ((gdouble) hc->wave_period) - 1);
1068 /* Get the the three different frequency components of the throughput (scaled by average
1069 * throughput). Our "error" estimate (the amount of noise that might be present in the
1070 * frequency band we're really interested in) is the average of the adjacent bands. */
1071 throughput_wave_component = mono_double_complex_scalar_div (hill_climbing_get_wave_component (worker, hc->samples, sample_count, hc->wave_period), average_throughput);
1072 throughput_error_estimate = cabs (mono_double_complex_scalar_div (hill_climbing_get_wave_component (worker, hc->samples, sample_count, adjacent_period_1), average_throughput));
1074 if (adjacent_period_2 <= sample_count) {
1075 throughput_error_estimate = MAX (throughput_error_estimate, cabs (mono_double_complex_scalar_div (hill_climbing_get_wave_component (
1076 worker, hc->samples, sample_count, adjacent_period_2), average_throughput)));
1079 /* Do the same for the thread counts, so we have something to compare to. We don't
1080 * measure thread count noise, because there is none; these are exact measurements. */
1081 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);
1083 /* Update our moving average of the throughput noise. We'll use this
1084 * later as feedback to determine the new size of the thread wave. */
1085 if (hc->average_throughput_noise == 0) {
1086 hc->average_throughput_noise = throughput_error_estimate;
1088 hc->average_throughput_noise = (hc->throughput_error_smoothing_factor * throughput_error_estimate)
1089 + ((1.0 + hc->throughput_error_smoothing_factor) * hc->average_throughput_noise);
1092 if (cabs (thread_wave_component) > 0) {
1093 /* Adjust the throughput wave so it's centered around the target wave,
1094 * and then calculate the adjusted throughput/thread ratio. */
1095 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);
1096 transition = TRANSITION_CLIMBING_MOVE;
1098 ratio = mono_double_complex_make (0, 0);
1099 transition = TRANSITION_STABILIZING;
1102 noise_for_confidence = MAX (hc->average_throughput_noise, throughput_error_estimate);
1103 if (noise_for_confidence > 0) {
1104 confidence = cabs (thread_wave_component) / noise_for_confidence / hc->target_signal_to_noise_ratio;
1106 /* there is no noise! */
1112 /* We use just the real part of the complex ratio we just calculated. If the throughput signal
1113 * is exactly in phase with the thread signal, this will be the same as taking the magnitude of
1114 * the complex move and moving that far up. If they're 180 degrees out of phase, we'll move
1115 * backward (because this indicates that our changes are having the opposite of the intended effect).
1116 * If they're 90 degrees out of phase, we won't move at all, because we can't tell wether we're
1117 * having a negative or positive effect on throughput. */
1118 move = creal (ratio);
1119 move = CLAMP (move, -1.0, 1.0);
1121 /* Apply our confidence multiplier. */
1122 move *= CLAMP (confidence, -1.0, 1.0);
1124 /* Now apply non-linear gain, such that values around zero are attenuated, while higher values
1125 * are enhanced. This allows us to move quickly if we're far away from the target, but more slowly
1126 * if we're getting close, giving us rapid ramp-up without wild oscillations around the target. */
1127 gain = hc->max_change_per_second * sample_duration;
1128 move = pow (fabs (move), hc->gain_exponent) * (move >= 0.0 ? 1 : -1) * gain;
1129 move = MIN (move, hc->max_change_per_sample);
1131 /* If the result was positive, and CPU is > 95%, refuse the move. */
1132 if (move > 0.0 && worker->cpu_usage > CPU_USAGE_HIGH)
1135 /* Apply the move to our control setting. */
1136 hc->current_control_setting += move;
1138 /* Calculate the new thread wave magnitude, which is based on the moving average we've been keeping of the
1139 * throughput error. This average starts at zero, so we'll start with a nice safe little wave at first. */
1140 new_thread_wave_magnitude = (gint)(0.5 + (hc->current_control_setting * hc->average_throughput_noise
1141 * hc->target_signal_to_noise_ratio * hc->thread_magnitude_multiplier * 2.0));
1142 new_thread_wave_magnitude = CLAMP (new_thread_wave_magnitude, 1, hc->max_thread_wave_magnitude);
1144 /* Make sure our control setting is within the MonoThreadPoolWorker's limits. */
1145 hc->current_control_setting = CLAMP (hc->current_control_setting, worker->limit_worker_min, worker->limit_worker_max - new_thread_wave_magnitude);
1147 /* Calculate the new thread count (control setting + square wave). */
1148 new_thread_count = (gint)(hc->current_control_setting + new_thread_wave_magnitude * ((hc->total_samples / (hc->wave_period / 2)) % 2));
1150 /* Make sure the new thread count doesn't exceed the MonoThreadPoolWorker's limits. */
1151 new_thread_count = CLAMP (new_thread_count, worker->limit_worker_min, worker->limit_worker_max);
1153 if (new_thread_count != current_thread_count)
1154 hill_climbing_change_thread_count (worker, new_thread_count, transition);
1156 if (creal (ratio) < 0.0 && new_thread_count == worker->limit_worker_min)
1157 *adjustment_interval = (gint)(0.5 + hc->current_sample_interval * (10.0 * MAX (-1.0 * creal (ratio), 1.0)));
1159 *adjustment_interval = hc->current_sample_interval;
1161 return new_thread_count;
1165 heuristic_should_adjust (MonoThreadPoolWorker *worker)
1167 if (worker->heuristic_last_dequeue > worker->heuristic_last_adjustment + worker->heuristic_adjustment_interval) {
1168 ThreadPoolWorkerCounter counter;
1169 counter = COUNTER_READ (worker);
1170 if (counter._.working <= counter._.max_working)
1178 heuristic_adjust (MonoThreadPoolWorker *worker)
1180 if (mono_coop_mutex_trylock (&worker->heuristic_lock) == 0) {
1181 gint32 completions = InterlockedExchange (&worker->heuristic_completions, 0);
1182 gint64 sample_end = mono_msec_ticks ();
1183 gint64 sample_duration = sample_end - worker->heuristic_sample_start;
1185 if (sample_duration >= worker->heuristic_adjustment_interval / 2) {
1186 ThreadPoolWorkerCounter counter;
1187 gint16 new_thread_count;
1189 counter = COUNTER_READ (worker);
1190 new_thread_count = hill_climbing_update (worker, counter._.max_working, sample_duration, completions, &worker->heuristic_adjustment_interval);
1192 COUNTER_ATOMIC (worker, counter, {
1193 counter._.max_working = new_thread_count;
1196 if (new_thread_count > counter._.max_working)
1197 worker_request (worker);
1199 worker->heuristic_sample_start = sample_end;
1200 worker->heuristic_last_adjustment = mono_msec_ticks ();
1203 mono_coop_mutex_unlock (&worker->heuristic_lock);
1208 heuristic_notify_work_completed (MonoThreadPoolWorker *worker)
1212 InterlockedIncrement (&worker->heuristic_completions);
1213 worker->heuristic_last_dequeue = mono_msec_ticks ();
1215 if (heuristic_should_adjust (worker))
1216 heuristic_adjust (worker);
1220 mono_threadpool_worker_notify_completed (MonoThreadPoolWorker *worker)
1222 ThreadPoolWorkerCounter counter;
1224 heuristic_notify_work_completed (worker);
1226 counter = COUNTER_READ (worker);
1227 return counter._.working <= counter._.max_working;
1231 mono_threadpool_worker_get_min (MonoThreadPoolWorker *worker)
1233 return worker->limit_worker_min;
1237 mono_threadpool_worker_set_min (MonoThreadPoolWorker *worker, gint32 value)
1239 if (value <= 0 || value > worker->limit_worker_max)
1242 worker->limit_worker_min = value;
1247 mono_threadpool_worker_get_max (MonoThreadPoolWorker *worker)
1249 return worker->limit_worker_max;
1253 mono_threadpool_worker_set_max (MonoThreadPoolWorker *worker, gint32 value)
1255 gint32 cpu_count = mono_cpu_count ();
1257 if (value < worker->limit_worker_min || value < cpu_count)
1260 worker->limit_worker_max = value;
1265 mono_threadpool_worker_set_suspended (MonoThreadPoolWorker *worker, gboolean suspended)
1267 worker->suspended = suspended;
1269 worker_request (worker);