[threadpool] Split domain and worker management (#4117)
[mono.git] / mono / metadata / threadpool-worker-default.c
1 /*
2  * threadpool-worker.c: native threadpool worker
3  *
4  * Author:
5  *      Ludovic Henry (ludovic.henry@xamarin.com)
6  *
7  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
8  */
9
10 #include <stdlib.h>
11 #define _USE_MATH_DEFINES // needed by MSVC to define math constants
12 #include <math.h>
13 #include <config.h>
14 #include <glib.h>
15
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
37 #define CPU_USAGE_LOW 80
38 #define CPU_USAGE_HIGH 95
39
40 #define MONITOR_INTERVAL 500 // ms
41 #define MONITOR_MINIMAL_LIFETIME 60 * 1000 // ms
42
43 #define WORKER_CREATION_MAX_PER_SEC 10
44
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.
47  * default: 2.0 */
48 #define HILL_CLIMBING_GAIN_EXPONENT 2.0
49
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.
52  * default: 0.15 */
53 #define HILL_CLIMBING_BIAS 0.15
54
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
66
67 typedef enum {
68         TRANSITION_WARMUP,
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,
76         TRANSITION_UNDEFINED,
77 } ThreadPoolHeuristicStateTransition;
78
79 typedef struct {
80         gint32 wave_period;
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;
93
94         gdouble current_control_setting;
95         gint64 total_samples;
96         gint16 last_thread_count;
97         gdouble elapsed_since_last_change;
98         gdouble completions_since_last_change;
99
100         gdouble average_throughput_noise;
101
102         gdouble *samples;
103         gdouble *thread_counts;
104
105         guint32 current_sample_interval;
106         gpointer random_interval_generator;
107
108         gint32 accumulated_completion_count;
109         gdouble accumulated_sample_duration;
110 } ThreadPoolHillClimbing;
111
112 typedef struct {
113         MonoThreadPoolWorkerCallback callback;
114         gpointer data;
115 } ThreadPoolWorkItem;
116
117 typedef union {
118         struct {
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 */
123         } _;
124         gint64 as_gint64;
125 } ThreadPoolWorkerCounter;
126
127 typedef MonoInternalThread ThreadPoolWorkerThread;
128
129 struct MonoThreadPoolWorker {
130         MonoRefCount ref;
131
132         ThreadPoolWorkerCounter counters;
133
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;
139
140         ThreadPoolWorkItem *work_items; // ThreadPoolWorkItem []
141         gint32 work_items_count;
142         gint32 work_items_size;
143         MonoCoopMutex work_items_lock;
144
145         guint32 worker_creation_current_second;
146         guint32 worker_creation_current_count;
147         MonoCoopMutex worker_creation_lock;
148
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;
156
157         gint32 limit_worker_min;
158         gint32 limit_worker_max;
159
160         MonoCpuUsageState *cpu_usage_state;
161         gint32 cpu_usage;
162
163         /* suspended by the debugger */
164         gboolean suspended;
165
166         gint32 monitor_status;
167 };
168
169 enum {
170         MONITOR_STATUS_REQUESTED,
171         MONITOR_STATUS_WAITING_FOR_REQUEST,
172         MONITOR_STATUS_NOT_RUNNING,
173 };
174
175 #define COUNTER_CHECK(counter) \
176         do { \
177                 g_assert (counter._.max_working > 0); \
178                 g_assert (counter._.starting >= 0); \
179                 g_assert (counter._.working >= 0); \
180         } while (0)
181
182 #define COUNTER_ATOMIC(worker,var,block) \
183         do { \
184                 ThreadPoolWorkerCounter __old; \
185                 do { \
186                         g_assert (worker); \
187                         __old = COUNTER_READ (worker); \
188                         (var) = __old; \
189                         { block; } \
190                         COUNTER_CHECK (var); \
191                 } while (InterlockedCompareExchange64 (&worker->counters.as_gint64, (var).as_gint64, __old.as_gint64) != __old.as_gint64); \
192         } while (0)
193
194 static inline ThreadPoolWorkerCounter
195 COUNTER_READ (MonoThreadPoolWorker *worker)
196 {
197         ThreadPoolWorkerCounter counter;
198         counter.as_gint64 = InterlockedRead64 (&worker->counters.as_gint64);
199         return counter;
200 }
201
202 static gpointer
203 rand_create (void)
204 {
205         mono_rand_open ();
206         return mono_rand_init (NULL, 0);
207 }
208
209 static guint32
210 rand_next (gpointer *handle, guint32 min, guint32 max)
211 {
212         MonoError error;
213         guint32 val;
214         mono_rand_try_get_uint32 (handle, &val, min, max, &error);
215         // FIXME handle error
216         mono_error_assert_ok (&error);
217         return val;
218 }
219
220 static void
221 destroy (gpointer data)
222 {
223         MonoThreadPoolWorker *worker;
224
225         worker = (MonoThreadPoolWorker*) data;
226         g_assert (worker);
227
228         // FIXME destroy everything
229
230         g_free (worker);
231 }
232
233 void
234 mono_threadpool_worker_init (MonoThreadPoolWorker **worker)
235 {
236         MonoThreadPoolWorker *wk;
237         ThreadPoolHillClimbing *hc;
238         const char *threads_per_cpu_env;
239         gint threads_per_cpu;
240         gint threads_count;
241
242         g_assert (worker);
243
244         wk = *worker = g_new0 (MonoThreadPoolWorker, 1);
245
246         mono_refcount_init (wk, destroy);
247
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);
253
254         /* wk->work_items_size is inited to 0 */
255         mono_coop_mutex_init (&wk->work_items_lock);
256
257         wk->worker_creation_current_second = -1;
258         mono_coop_mutex_init (&wk->worker_creation_lock);
259
260         wk->heuristic_adjustment_interval = 10;
261         mono_coop_mutex_init (&wk->heuristic_lock);
262
263         mono_rand_open ();
264
265         hc = &wk->heuristic_hill_climbing;
266
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);
291
292         if (!(threads_per_cpu_env = g_getenv ("MONO_THREADS_PER_CPU")))
293                 threads_per_cpu = 1;
294         else
295                 threads_per_cpu = CLAMP (atoi (threads_per_cpu_env), 1, 50);
296
297         threads_count = mono_cpu_count () * threads_per_cpu;
298
299         wk->limit_worker_min = threads_count;
300
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));
303 #else
304         wk->limit_worker_max = threads_count * 100;
305 #endif
306
307         wk->counters._.max_working = wk->limit_worker_min;
308
309         wk->cpu_usage_state = g_new0 (MonoCpuUsageState, 1);
310
311         wk->suspended = FALSE;
312
313         wk->monitor_status = MONITOR_STATUS_NOT_RUNNING;
314 }
315
316 void
317 mono_threadpool_worker_cleanup (MonoThreadPoolWorker *worker)
318 {
319         MonoInternalThread *current;
320
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 ());
324
325         current = mono_thread_internal_current ();
326
327         while (worker->monitor_status != MONITOR_STATUS_NOT_RUNNING)
328                 mono_thread_info_sleep (1, NULL);
329
330         mono_coop_mutex_lock (&worker->threads_lock);
331
332         /* unpark all worker->parked_threads */
333         mono_coop_cond_broadcast (&worker->parked_threads_cond);
334
335         for (;;) {
336                 ThreadPoolWorkerCounter counter;
337
338                 counter = COUNTER_READ (worker);
339                 if (counter._.starting + counter._.working + counter._.parked == 0)
340                         break;
341
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 */
345                                 break;
346                         }
347                 }
348
349                 mono_coop_cond_wait (&worker->threads_exit_cond, &worker->threads_lock);
350         }
351
352         mono_coop_mutex_unlock (&worker->threads_lock);
353
354         mono_refcount_dec (worker);
355 }
356
357 static void
358 work_item_lock (MonoThreadPoolWorker *worker)
359 {
360         mono_coop_mutex_lock (&worker->work_items_lock);
361 }
362
363 static void
364 work_item_unlock (MonoThreadPoolWorker *worker)
365 {
366         mono_coop_mutex_unlock (&worker->work_items_lock);
367 }
368
369 static void
370 work_item_push (MonoThreadPoolWorker *worker, MonoThreadPoolWorkerCallback callback, gpointer data)
371 {
372         ThreadPoolWorkItem work_item;
373
374         g_assert (worker);
375         g_assert (callback);
376
377         work_item.callback = callback;
378         work_item.data = data;
379
380         work_item_lock (worker);
381
382         g_assert (worker->work_items_count <= worker->work_items_size);
383
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);
387         }
388
389         g_assert (worker->work_items);
390
391         worker->work_items [worker->work_items_count ++] = work_item;
392
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);
395
396         work_item_unlock (worker);
397 }
398
399 static gboolean
400 work_item_try_pop (MonoThreadPoolWorker *worker, ThreadPoolWorkItem *work_item)
401 {
402         g_assert (worker);
403         g_assert (work_item);
404
405         work_item_lock (worker);
406
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);
409
410         if (worker->work_items_count == 0) {
411                 work_item_unlock (worker);
412                 return FALSE;
413         }
414
415         *work_item = worker->work_items [-- worker->work_items_count];
416
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);
420         }
421
422         work_item_unlock (worker);
423
424         return TRUE;
425 }
426
427 static gint32
428 work_item_count (MonoThreadPoolWorker *worker)
429 {
430         gint32 count;
431
432         work_item_lock (worker);
433         count = worker->work_items_count;
434         work_item_unlock (worker);
435
436         return count;
437 }
438
439 static void worker_request (MonoThreadPoolWorker *worker);
440
441 void
442 mono_threadpool_worker_enqueue (MonoThreadPoolWorker *worker, MonoThreadPoolWorkerCallback callback, gpointer data)
443 {
444         work_item_push (worker, callback, data);
445
446         worker_request (worker);
447 }
448
449 static void
450 worker_wait_interrupt (gpointer data)
451 {
452         MonoThreadPoolWorker *worker;
453
454         worker = (MonoThreadPoolWorker*) data;
455         g_assert (worker);
456
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);
460
461         mono_refcount_dec (worker);
462 }
463
464 /* return TRUE if timeout, FALSE otherwise (worker unpark or interrupt) */
465 static gboolean
466 worker_park (MonoThreadPoolWorker *worker)
467 {
468         gboolean timeout = FALSE;
469
470         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] worker parking", mono_native_thread_id_get ());
471
472         mono_coop_mutex_lock (&worker->threads_lock);
473
474         if (!mono_runtime_is_shutting_down ()) {
475                 static gpointer rand_handle = NULL;
476                 MonoInternalThread *thread;
477                 gboolean interrupted = FALSE;
478                 ThreadPoolWorkerCounter counter;
479
480                 if (!rand_handle)
481                         rand_handle = rand_create ();
482                 g_assert (rand_handle);
483
484                 thread = mono_thread_internal_current ();
485                 g_assert (thread);
486
487                 COUNTER_ATOMIC (worker, counter, {
488                         counter._.working --;
489                         counter._.parked ++;
490                 });
491
492                 worker->parked_threads_count += 1;
493
494                 mono_thread_info_install_interrupt (worker_wait_interrupt, mono_refcount_inc (worker), &interrupted);
495                 if (interrupted) {
496                         mono_refcount_dec (worker);
497                         goto done;
498                 }
499
500                 if (mono_coop_cond_timedwait (&worker->parked_threads_cond, &worker->threads_lock, rand_next (&rand_handle, 5 * 1000, 60 * 1000)) != 0)
501                         timeout = TRUE;
502
503                 mono_thread_info_uninstall_interrupt (&interrupted);
504                 if (!interrupted)
505                         mono_refcount_dec (worker);
506
507 done:
508                 worker->parked_threads_count -= 1;
509
510                 COUNTER_ATOMIC (worker, counter, {
511                         counter._.working ++;
512                         counter._.parked --;
513                 });
514         }
515
516         mono_coop_mutex_unlock (&worker->threads_lock);
517
518         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] worker unparking, timeout? %s", mono_native_thread_id_get (), timeout ? "yes" : "no");
519
520         return timeout;
521 }
522
523 static gboolean
524 worker_try_unpark (MonoThreadPoolWorker *worker)
525 {
526         gboolean res = FALSE;
527
528         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try unpark worker", mono_native_thread_id_get ());
529
530         mono_coop_mutex_lock (&worker->threads_lock);
531         if (worker->parked_threads_count > 0) {
532                 mono_coop_cond_signal (&worker->parked_threads_cond);
533                 res = TRUE;
534         }
535         mono_coop_mutex_unlock (&worker->threads_lock);
536
537         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try unpark worker, success? %s", mono_native_thread_id_get (), res ? "yes" : "no");
538
539         return res;
540 }
541
542 static void
543 worker_thread (gpointer data)
544 {
545         MonoThreadPoolWorker *worker;
546         MonoError error;
547         MonoInternalThread *thread;
548         ThreadPoolWorkerCounter counter;
549
550         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_THREADPOOL, "[%p] worker starting", mono_native_thread_id_get ());
551
552         worker = (MonoThreadPoolWorker*) data;
553         g_assert (worker);
554
555         COUNTER_ATOMIC (worker, counter, {
556                 counter._.starting --;
557                 counter._.working ++;
558         });
559
560         thread = mono_thread_internal_current ();
561         g_assert (thread);
562
563         mono_coop_mutex_lock (&worker->threads_lock);
564         g_ptr_array_add (worker->threads, thread);
565         mono_coop_mutex_unlock (&worker->threads_lock);
566
567         mono_thread_set_name_internal (thread, mono_string_new (mono_get_root_domain (), "Threadpool worker"), FALSE, &error);
568         mono_error_assert_ok (&error);
569
570         while (!mono_runtime_is_shutting_down ()) {
571                 ThreadPoolWorkItem work_item;
572
573                 if (mono_thread_interruption_checkpoint ())
574                         continue;
575
576                 if (!work_item_try_pop (worker, &work_item)) {
577                         gboolean timeout;
578
579                         timeout = worker_park (worker);
580                         if (timeout)
581                                 break;
582
583                         continue;
584                 }
585
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);
588
589                 work_item.callback (work_item.data);
590         }
591
592         mono_coop_mutex_lock (&worker->threads_lock);
593
594         COUNTER_ATOMIC (worker, counter, {
595                 counter._.working --;
596         });
597
598         g_ptr_array_remove (worker->threads, thread);
599
600         mono_coop_cond_signal (&worker->threads_exit_cond);
601
602         mono_coop_mutex_unlock (&worker->threads_lock);
603
604         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_THREADPOOL, "[%p] worker finishing", mono_native_thread_id_get ());
605
606         mono_refcount_dec (worker);
607 }
608
609 static gboolean
610 worker_try_create (MonoThreadPoolWorker *worker)
611 {
612         MonoError error;
613         MonoInternalThread *thread;
614         gint64 current_ticks;
615         gint32 now;
616         ThreadPoolWorkerCounter counter;
617
618         if (mono_runtime_is_shutting_down ())
619                 return FALSE;
620
621         mono_coop_mutex_lock (&worker->worker_creation_lock);
622
623         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker", mono_native_thread_id_get ());
624
625         current_ticks = mono_100ns_ticks ();
626         if (0 == current_ticks) {
627                 g_warning ("failed to get 100ns ticks");
628         } else {
629                 now = current_ticks / (10 * 1000 * 1000);
630                 if (worker->worker_creation_current_second != now) {
631                         worker->worker_creation_current_second = now;
632                         worker->worker_creation_current_count = 0;
633                 } else {
634                         g_assert (worker->worker_creation_current_count <= WORKER_CREATION_MAX_PER_SEC);
635                         if (worker->worker_creation_current_count == WORKER_CREATION_MAX_PER_SEC) {
636                                 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",
637                                         mono_native_thread_id_get (), worker->worker_creation_current_count);
638                                 mono_coop_mutex_unlock (&worker->worker_creation_lock);
639                                 return FALSE;
640                         }
641                 }
642         }
643
644         COUNTER_ATOMIC (worker, counter, {
645                 if (counter._.working >= counter._.max_working) {
646                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker, failed: maximum number of working threads reached",
647                                 mono_native_thread_id_get ());
648                         mono_coop_mutex_unlock (&worker->worker_creation_lock);
649                         return FALSE;
650                 }
651                 counter._.starting ++;
652         });
653
654         thread = mono_thread_create_internal (mono_get_root_domain (), worker_thread, mono_refcount_inc (worker), TRUE, 0, &error);
655         if (!thread) {
656                 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));
657                 mono_error_cleanup (&error);
658
659                 COUNTER_ATOMIC (worker, counter, {
660                         counter._.starting --;
661                 });
662
663                 mono_coop_mutex_unlock (&worker->worker_creation_lock);
664
665                 mono_refcount_dec (worker);
666
667                 return FALSE;
668         }
669
670         worker->worker_creation_current_count += 1;
671
672         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker, created %p, now = %d count = %d",
673                 mono_native_thread_id_get (), (gpointer) thread->tid, now, worker->worker_creation_current_count);
674
675         mono_coop_mutex_unlock (&worker->worker_creation_lock);
676         return TRUE;
677 }
678
679 static void monitor_ensure_running (MonoThreadPoolWorker *worker);
680
681 static void
682 worker_request (MonoThreadPoolWorker *worker)
683 {
684         g_assert (worker);
685
686         if (worker->suspended)
687                 return;
688
689         monitor_ensure_running (worker);
690
691         if (worker_try_unpark (worker)) {
692                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] request worker, unparked", mono_native_thread_id_get ());
693                 return;
694         }
695
696         if (worker_try_create (worker)) {
697                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] request worker, created", mono_native_thread_id_get ());
698                 return;
699         }
700
701         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] request worker, failed", mono_native_thread_id_get ());
702 }
703
704 static gboolean
705 monitor_should_keep_running (MonoThreadPoolWorker *worker)
706 {
707         static gint64 last_should_keep_running = -1;
708
709         g_assert (worker->monitor_status == MONITOR_STATUS_WAITING_FOR_REQUEST || worker->monitor_status == MONITOR_STATUS_REQUESTED);
710
711         if (InterlockedExchange (&worker->monitor_status, MONITOR_STATUS_WAITING_FOR_REQUEST) == MONITOR_STATUS_WAITING_FOR_REQUEST) {
712                 gboolean should_keep_running = TRUE, force_should_keep_running = FALSE;
713
714                 if (mono_runtime_is_shutting_down ()) {
715                         should_keep_running = FALSE;
716                 } else {
717                         if (work_item_count (worker) == 0)
718                                 should_keep_running = FALSE;
719
720                         if (!should_keep_running) {
721                                 if (last_should_keep_running == -1 || mono_100ns_ticks () - last_should_keep_running < MONITOR_MINIMAL_LIFETIME * 1000 * 10) {
722                                         should_keep_running = force_should_keep_running = TRUE;
723                                 }
724                         }
725                 }
726
727                 if (should_keep_running) {
728                         if (last_should_keep_running == -1 || !force_should_keep_running)
729                                 last_should_keep_running = mono_100ns_ticks ();
730                 } else {
731                         last_should_keep_running = -1;
732                         if (InterlockedCompareExchange (&worker->monitor_status, MONITOR_STATUS_NOT_RUNNING, MONITOR_STATUS_WAITING_FOR_REQUEST) == MONITOR_STATUS_WAITING_FOR_REQUEST)
733                                 return FALSE;
734                 }
735         }
736
737         g_assert (worker->monitor_status == MONITOR_STATUS_WAITING_FOR_REQUEST || worker->monitor_status == MONITOR_STATUS_REQUESTED);
738
739         return TRUE;
740 }
741
742 static gboolean
743 monitor_sufficient_delay_since_last_dequeue (MonoThreadPoolWorker *worker)
744 {
745         gint64 threshold;
746
747         g_assert (worker);
748
749         if (worker->cpu_usage < CPU_USAGE_LOW) {
750                 threshold = MONITOR_INTERVAL;
751         } else {
752                 ThreadPoolWorkerCounter counter;
753                 counter = COUNTER_READ (worker);
754                 threshold = counter._.max_working * MONITOR_INTERVAL * 2;
755         }
756
757         return mono_msec_ticks () >= worker->heuristic_last_dequeue + threshold;
758 }
759
760 static void hill_climbing_force_change (MonoThreadPoolWorker *worker, gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition);
761
762 static void
763 monitor_thread (gpointer data)
764 {
765         MonoThreadPoolWorker *worker;
766         MonoInternalThread *internal;
767         guint i;
768
769         worker = (MonoThreadPoolWorker*) data;
770         g_assert (worker);
771
772         internal = mono_thread_internal_current ();
773         g_assert (internal);
774
775         mono_cpu_usage (worker->cpu_usage_state);
776
777         // printf ("monitor_thread: start\n");
778
779         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, started", mono_native_thread_id_get ());
780
781         do {
782                 ThreadPoolWorkerCounter counter;
783                 gboolean limit_worker_max_reached;
784                 gint32 interval_left = MONITOR_INTERVAL;
785                 gint32 awake = 0; /* number of spurious awakes we tolerate before doing a round of rebalancing */
786
787                 g_assert (worker->monitor_status != MONITOR_STATUS_NOT_RUNNING);
788
789                 // counter = COUNTER_READ (worker);
790                 // printf ("monitor_thread: starting = %d working = %d parked = %d max_working = %d\n",
791                 //      counter._.starting, counter._.working, counter._.parked, counter._.max_working);
792
793                 do {
794                         gint64 ts;
795                         gboolean alerted = FALSE;
796
797                         if (mono_runtime_is_shutting_down ())
798                                 break;
799
800                         ts = mono_msec_ticks ();
801                         if (mono_thread_info_sleep (interval_left, &alerted) == 0)
802                                 break;
803                         interval_left -= mono_msec_ticks () - ts;
804
805                         g_assert (!(internal->state & ThreadState_StopRequested));
806                         mono_thread_interruption_checkpoint ();
807                 } while (interval_left > 0 && ++awake < 10);
808
809                 if (mono_runtime_is_shutting_down ())
810                         continue;
811
812                 if (worker->suspended)
813                         continue;
814
815                 if (work_item_count (worker) == 0)
816                         continue;
817
818                 worker->cpu_usage = mono_cpu_usage (worker->cpu_usage_state);
819
820                 if (!monitor_sufficient_delay_since_last_dequeue (worker))
821                         continue;
822
823                 limit_worker_max_reached = FALSE;
824
825                 COUNTER_ATOMIC (worker, counter, {
826                         if (counter._.max_working >= worker->limit_worker_max) {
827                                 limit_worker_max_reached = TRUE;
828                                 break;
829                         }
830                         counter._.max_working ++;
831                 });
832
833                 if (limit_worker_max_reached)
834                         continue;
835
836                 hill_climbing_force_change (worker, counter._.max_working, TRANSITION_STARVATION);
837
838                 for (i = 0; i < 5; ++i) {
839                         if (mono_runtime_is_shutting_down ())
840                                 break;
841
842                         if (worker_try_unpark (worker)) {
843                                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, unparked", mono_native_thread_id_get ());
844                                 break;
845                         }
846
847                         if (worker_try_create (worker)) {
848                                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, created", mono_native_thread_id_get ());
849                                 break;
850                         }
851                 }
852         } while (monitor_should_keep_running (worker));
853
854         // printf ("monitor_thread: stop\n");
855
856         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, finished", mono_native_thread_id_get ());
857 }
858
859 static void
860 monitor_ensure_running (MonoThreadPoolWorker *worker)
861 {
862         MonoError error;
863         for (;;) {
864                 switch (worker->monitor_status) {
865                 case MONITOR_STATUS_REQUESTED:
866                         // printf ("monitor_thread: requested\n");
867                         return;
868                 case MONITOR_STATUS_WAITING_FOR_REQUEST:
869                         // printf ("monitor_thread: waiting for request\n");
870                         InterlockedCompareExchange (&worker->monitor_status, MONITOR_STATUS_REQUESTED, MONITOR_STATUS_WAITING_FOR_REQUEST);
871                         break;
872                 case MONITOR_STATUS_NOT_RUNNING:
873                         // printf ("monitor_thread: not running\n");
874                         if (mono_runtime_is_shutting_down ())
875                                 return;
876                         if (InterlockedCompareExchange (&worker->monitor_status, MONITOR_STATUS_REQUESTED, MONITOR_STATUS_NOT_RUNNING) == MONITOR_STATUS_NOT_RUNNING) {
877                                 // printf ("monitor_thread: creating\n");
878                                 if (!mono_thread_create_internal (mono_get_root_domain (), monitor_thread, worker, TRUE, SMALL_STACK, &error)) {
879                                         // printf ("monitor_thread: creating failed\n");
880                                         worker->monitor_status = MONITOR_STATUS_NOT_RUNNING;
881                                         mono_error_cleanup (&error);
882                                 }
883                                 return;
884                         }
885                         break;
886                 default: g_assert_not_reached ();
887                 }
888         }
889 }
890
891 static void
892 hill_climbing_change_thread_count (MonoThreadPoolWorker *worker, gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition)
893 {
894         ThreadPoolHillClimbing *hc;
895
896         g_assert (worker);
897
898         hc = &worker->heuristic_hill_climbing;
899
900         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);
901
902         hc->last_thread_count = new_thread_count;
903         hc->current_sample_interval = rand_next (&hc->random_interval_generator, hc->sample_interval_low, hc->sample_interval_high);
904         hc->elapsed_since_last_change = 0;
905         hc->completions_since_last_change = 0;
906 }
907
908 static void
909 hill_climbing_force_change (MonoThreadPoolWorker *worker, gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition)
910 {
911         ThreadPoolHillClimbing *hc;
912
913         g_assert (worker);
914
915         hc = &worker->heuristic_hill_climbing;
916
917         if (new_thread_count != hc->last_thread_count) {
918                 hc->current_control_setting += new_thread_count - hc->last_thread_count;
919                 hill_climbing_change_thread_count (worker, new_thread_count, transition);
920         }
921 }
922
923 static double_complex
924 hill_climbing_get_wave_component (MonoThreadPoolWorker *worker, gdouble *samples, guint sample_count, gdouble period)
925 {
926         ThreadPoolHillClimbing *hc;
927         gdouble w, cosine, sine, coeff, q0, q1, q2;
928         guint i;
929
930         g_assert (worker);
931         g_assert (sample_count >= period);
932         g_assert (period >= 2);
933
934         hc = &worker->heuristic_hill_climbing;
935
936         w = 2.0 * M_PI / period;
937         cosine = cos (w);
938         sine = sin (w);
939         coeff = 2.0 * cosine;
940         q0 = q1 = q2 = 0;
941
942         for (i = 0; i < sample_count; ++i) {
943                 q0 = coeff * q1 - q2 + samples [(hc->total_samples - sample_count + i) % hc->samples_to_measure];
944                 q2 = q1;
945                 q1 = q0;
946         }
947
948         return mono_double_complex_scalar_div (mono_double_complex_make (q1 - q2 * cosine, (q2 * sine)), ((gdouble)sample_count));
949 }
950
951 static gint16
952 hill_climbing_update (MonoThreadPoolWorker *worker, gint16 current_thread_count, guint32 sample_duration, gint32 completions, gint64 *adjustment_interval)
953 {
954         ThreadPoolHillClimbing *hc;
955         ThreadPoolHeuristicStateTransition transition;
956         gdouble throughput;
957         gdouble throughput_error_estimate;
958         gdouble confidence;
959         gdouble move;
960         gdouble gain;
961         gint sample_index;
962         gint sample_count;
963         gint new_thread_wave_magnitude;
964         gint new_thread_count;
965         double_complex thread_wave_component;
966         double_complex throughput_wave_component;
967         double_complex ratio;
968
969         g_assert (worker);
970         g_assert (adjustment_interval);
971
972         hc = &worker->heuristic_hill_climbing;
973
974         /* If someone changed the thread count without telling us, update our records accordingly. */
975         if (current_thread_count != hc->last_thread_count)
976                 hill_climbing_force_change (worker, current_thread_count, TRANSITION_INITIALIZING);
977
978         /* Update the cumulative stats for this thread count */
979         hc->elapsed_since_last_change += sample_duration;
980         hc->completions_since_last_change += completions;
981
982         /* Add in any data we've already collected about this sample */
983         sample_duration += hc->accumulated_sample_duration;
984         completions += hc->accumulated_completion_count;
985
986         /* We need to make sure we're collecting reasonably accurate data. Since we're just counting the end
987          * of each work item, we are goinng to be missing some data about what really happened during the
988          * sample interval. The count produced by each thread includes an initial work item that may have
989          * started well before the start of the interval, and each thread may have been running some new
990          * work item for some time before the end of the interval, which did not yet get counted. So
991          * our count is going to be off by +/- threadCount workitems.
992          *
993          * The exception is that the thread that reported to us last time definitely wasn't running any work
994          * at that time, and the thread that's reporting now definitely isn't running a work item now. So
995          * we really only need to consider threadCount-1 threads.
996          *
997          * Thus the percent error in our count is +/- (threadCount-1)/numCompletions.
998          *
999          * We cannot rely on the frequency-domain analysis we'll be doing later to filter out this error, because
1000          * of the way it accumulates over time. If this sample is off by, say, 33% in the negative direction,
1001          * then the next one likely will be too. The one after that will include the sum of the completions
1002          * we missed in the previous samples, and so will be 33% positive. So every three samples we'll have
1003          * two "low" samples and one "high" sample. This will appear as periodic variation right in the frequency
1004          * range we're targeting, which will not be filtered by the frequency-domain translation. */
1005         if (hc->total_samples > 0 && ((current_thread_count - 1.0) / completions) >= hc->max_sample_error) {
1006                 /* Not accurate enough yet. Let's accumulate the data so
1007                  * far, and tell the MonoThreadPoolWorker to collect a little more. */
1008                 hc->accumulated_sample_duration = sample_duration;
1009                 hc->accumulated_completion_count = completions;
1010                 *adjustment_interval = 10;
1011                 return current_thread_count;
1012         }
1013
1014         /* We've got enouugh data for our sample; reset our accumulators for next time. */
1015         hc->accumulated_sample_duration = 0;
1016         hc->accumulated_completion_count = 0;
1017
1018         /* Add the current thread count and throughput sample to our history. */
1019         throughput = ((gdouble) completions) / sample_duration;
1020
1021         sample_index = hc->total_samples % hc->samples_to_measure;
1022         hc->samples [sample_index] = throughput;
1023         hc->thread_counts [sample_index] = current_thread_count;
1024         hc->total_samples ++;
1025
1026         /* Set up defaults for our metrics. */
1027         thread_wave_component = mono_double_complex_make(0, 0);
1028         throughput_wave_component = mono_double_complex_make(0, 0);
1029         throughput_error_estimate = 0;
1030         ratio = mono_double_complex_make(0, 0);
1031         confidence = 0;
1032
1033         transition = TRANSITION_WARMUP;
1034
1035         /* How many samples will we use? It must be at least the three wave periods we're looking for, and it must also
1036          * be a whole multiple of the primary wave's period; otherwise the frequency we're looking for will fall between
1037          * two frequency bands in the Fourier analysis, and we won't be able to measure it accurately. */
1038         sample_count = ((gint) MIN (hc->total_samples - 1, hc->samples_to_measure) / hc->wave_period) * hc->wave_period;
1039
1040         if (sample_count > hc->wave_period) {
1041                 guint i;
1042                 gdouble average_throughput;
1043                 gdouble average_thread_count;
1044                 gdouble sample_sum = 0;
1045                 gdouble thread_sum = 0;
1046
1047                 /* Average the throughput and thread count samples, so we can scale the wave magnitudes later. */
1048                 for (i = 0; i < sample_count; ++i) {
1049                         guint j = (hc->total_samples - sample_count + i) % hc->samples_to_measure;
1050                         sample_sum += hc->samples [j];
1051                         thread_sum += hc->thread_counts [j];
1052                 }
1053
1054                 average_throughput = sample_sum / sample_count;
1055                 average_thread_count = thread_sum / sample_count;
1056
1057                 if (average_throughput > 0 && average_thread_count > 0) {
1058                         gdouble noise_for_confidence, adjacent_period_1, adjacent_period_2;
1059
1060                         /* Calculate the periods of the adjacent frequency bands we'll be using to
1061                          * measure noise levels. We want the two adjacent Fourier frequency bands. */
1062                         adjacent_period_1 = sample_count / (((gdouble) sample_count) / ((gdouble) hc->wave_period) + 1);
1063                         adjacent_period_2 = sample_count / (((gdouble) sample_count) / ((gdouble) hc->wave_period) - 1);
1064
1065                         /* Get the the three different frequency components of the throughput (scaled by average
1066                          * throughput). Our "error" estimate (the amount of noise that might be present in the
1067                          * frequency band we're really interested in) is the average of the adjacent bands. */
1068                         throughput_wave_component = mono_double_complex_scalar_div (hill_climbing_get_wave_component (worker, hc->samples, sample_count, hc->wave_period), average_throughput);
1069                         throughput_error_estimate = cabs (mono_double_complex_scalar_div (hill_climbing_get_wave_component (worker, hc->samples, sample_count, adjacent_period_1), average_throughput));
1070
1071                         if (adjacent_period_2 <= sample_count) {
1072                                 throughput_error_estimate = MAX (throughput_error_estimate, cabs (mono_double_complex_scalar_div (hill_climbing_get_wave_component (
1073                                         worker, hc->samples, sample_count, adjacent_period_2), average_throughput)));
1074                         }
1075
1076                         /* Do the same for the thread counts, so we have something to compare to. We don't
1077                          * measure thread count noise, because there is none; these are exact measurements. */
1078                         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);
1079
1080                         /* Update our moving average of the throughput noise. We'll use this
1081                          * later as feedback to determine the new size of the thread wave. */
1082                         if (hc->average_throughput_noise == 0) {
1083                                 hc->average_throughput_noise = throughput_error_estimate;
1084                         } else {
1085                                 hc->average_throughput_noise = (hc->throughput_error_smoothing_factor * throughput_error_estimate)
1086                                         + ((1.0 + hc->throughput_error_smoothing_factor) * hc->average_throughput_noise);
1087                         }
1088
1089                         if (cabs (thread_wave_component) > 0) {
1090                                 /* Adjust the throughput wave so it's centered around the target wave,
1091                                  * and then calculate the adjusted throughput/thread ratio. */
1092                                 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);
1093                                 transition = TRANSITION_CLIMBING_MOVE;
1094                         } else {
1095                                 ratio = mono_double_complex_make (0, 0);
1096                                 transition = TRANSITION_STABILIZING;
1097                         }
1098
1099                         noise_for_confidence = MAX (hc->average_throughput_noise, throughput_error_estimate);
1100                         if (noise_for_confidence > 0) {
1101                                 confidence = cabs (thread_wave_component) / noise_for_confidence / hc->target_signal_to_noise_ratio;
1102                         } else {
1103                                 /* there is no noise! */
1104                                 confidence = 1.0;
1105                         }
1106                 }
1107         }
1108
1109         /* We use just the real part of the complex ratio we just calculated. If the throughput signal
1110          * is exactly in phase with the thread signal, this will be the same as taking the magnitude of
1111          * the complex move and moving that far up. If they're 180 degrees out of phase, we'll move
1112          * backward (because this indicates that our changes are having the opposite of the intended effect).
1113          * If they're 90 degrees out of phase, we won't move at all, because we can't tell wether we're
1114          * having a negative or positive effect on throughput. */
1115         move = creal (ratio);
1116         move = CLAMP (move, -1.0, 1.0);
1117
1118         /* Apply our confidence multiplier. */
1119         move *= CLAMP (confidence, -1.0, 1.0);
1120
1121         /* Now apply non-linear gain, such that values around zero are attenuated, while higher values
1122          * are enhanced. This allows us to move quickly if we're far away from the target, but more slowly
1123         * if we're getting close, giving us rapid ramp-up without wild oscillations around the target. */
1124         gain = hc->max_change_per_second * sample_duration;
1125         move = pow (fabs (move), hc->gain_exponent) * (move >= 0.0 ? 1 : -1) * gain;
1126         move = MIN (move, hc->max_change_per_sample);
1127
1128         /* If the result was positive, and CPU is > 95%, refuse the move. */
1129         if (move > 0.0 && worker->cpu_usage > CPU_USAGE_HIGH)
1130                 move = 0.0;
1131
1132         /* Apply the move to our control setting. */
1133         hc->current_control_setting += move;
1134
1135         /* Calculate the new thread wave magnitude, which is based on the moving average we've been keeping of the
1136          * throughput error.  This average starts at zero, so we'll start with a nice safe little wave at first. */
1137         new_thread_wave_magnitude = (gint)(0.5 + (hc->current_control_setting * hc->average_throughput_noise
1138                 * hc->target_signal_to_noise_ratio * hc->thread_magnitude_multiplier * 2.0));
1139         new_thread_wave_magnitude = CLAMP (new_thread_wave_magnitude, 1, hc->max_thread_wave_magnitude);
1140
1141         /* Make sure our control setting is within the MonoThreadPoolWorker's limits. */
1142         hc->current_control_setting = CLAMP (hc->current_control_setting, worker->limit_worker_min, worker->limit_worker_max - new_thread_wave_magnitude);
1143
1144         /* Calculate the new thread count (control setting + square wave). */
1145         new_thread_count = (gint)(hc->current_control_setting + new_thread_wave_magnitude * ((hc->total_samples / (hc->wave_period / 2)) % 2));
1146
1147         /* Make sure the new thread count doesn't exceed the MonoThreadPoolWorker's limits. */
1148         new_thread_count = CLAMP (new_thread_count, worker->limit_worker_min, worker->limit_worker_max);
1149
1150         if (new_thread_count != current_thread_count)
1151                 hill_climbing_change_thread_count (worker, new_thread_count, transition);
1152
1153         if (creal (ratio) < 0.0 && new_thread_count == worker->limit_worker_min)
1154                 *adjustment_interval = (gint)(0.5 + hc->current_sample_interval * (10.0 * MAX (-1.0 * creal (ratio), 1.0)));
1155         else
1156                 *adjustment_interval = hc->current_sample_interval;
1157
1158         return new_thread_count;
1159 }
1160
1161 static gboolean
1162 heuristic_should_adjust (MonoThreadPoolWorker *worker)
1163 {
1164         if (worker->heuristic_last_dequeue > worker->heuristic_last_adjustment + worker->heuristic_adjustment_interval) {
1165                 ThreadPoolWorkerCounter counter;
1166                 counter = COUNTER_READ (worker);
1167                 if (counter._.working <= counter._.max_working)
1168                         return TRUE;
1169         }
1170
1171         return FALSE;
1172 }
1173
1174 static void
1175 heuristic_adjust (MonoThreadPoolWorker *worker)
1176 {
1177         if (mono_coop_mutex_trylock (&worker->heuristic_lock) == 0) {
1178                 gint32 completions = InterlockedExchange (&worker->heuristic_completions, 0);
1179                 gint64 sample_end = mono_msec_ticks ();
1180                 gint64 sample_duration = sample_end - worker->heuristic_sample_start;
1181
1182                 if (sample_duration >= worker->heuristic_adjustment_interval / 2) {
1183                         ThreadPoolWorkerCounter counter;
1184                         gint16 new_thread_count;
1185
1186                         counter = COUNTER_READ (worker);
1187                         new_thread_count = hill_climbing_update (worker, counter._.max_working, sample_duration, completions, &worker->heuristic_adjustment_interval);
1188
1189                         COUNTER_ATOMIC (worker, counter, {
1190                                 counter._.max_working = new_thread_count;
1191                         });
1192
1193                         if (new_thread_count > counter._.max_working)
1194                                 worker_request (worker);
1195
1196                         worker->heuristic_sample_start = sample_end;
1197                         worker->heuristic_last_adjustment = mono_msec_ticks ();
1198                 }
1199
1200                 mono_coop_mutex_unlock (&worker->heuristic_lock);
1201         }
1202 }
1203
1204 static void
1205 heuristic_notify_work_completed (MonoThreadPoolWorker *worker)
1206 {
1207         g_assert (worker);
1208
1209         InterlockedIncrement (&worker->heuristic_completions);
1210         worker->heuristic_last_dequeue = mono_msec_ticks ();
1211
1212         if (heuristic_should_adjust (worker))
1213                 heuristic_adjust (worker);
1214 }
1215
1216 gboolean
1217 mono_threadpool_worker_notify_completed (MonoThreadPoolWorker *worker)
1218 {
1219         ThreadPoolWorkerCounter counter;
1220
1221         heuristic_notify_work_completed (worker);
1222
1223         counter = COUNTER_READ (worker);
1224         return counter._.working <= counter._.max_working;
1225 }
1226
1227 gint32
1228 mono_threadpool_worker_get_min (MonoThreadPoolWorker *worker)
1229 {
1230         return worker->limit_worker_min;
1231 }
1232
1233 gboolean
1234 mono_threadpool_worker_set_min (MonoThreadPoolWorker *worker, gint32 value)
1235 {
1236         if (value <= 0 || value > worker->limit_worker_max)
1237                 return FALSE;
1238
1239         worker->limit_worker_min = value;
1240         return TRUE;
1241 }
1242
1243 gint32
1244 mono_threadpool_worker_get_max (MonoThreadPoolWorker *worker)
1245 {
1246         return worker->limit_worker_max;
1247 }
1248
1249 gboolean
1250 mono_threadpool_worker_set_max (MonoThreadPoolWorker *worker, gint32 value)
1251 {
1252         gint32 cpu_count = mono_cpu_count ();
1253
1254         if (value < worker->limit_worker_min || value < cpu_count)
1255                 return FALSE;
1256
1257         worker->limit_worker_max = value;
1258         return TRUE;
1259 }
1260
1261 void
1262 mono_threadpool_worker_set_suspended (MonoThreadPoolWorker *worker, gboolean suspended)
1263 {
1264         worker->suspended = suspended;
1265         if (!suspended)
1266                 worker_request (worker);
1267 }