2 * threadpool.c: global thread pool
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Gonzalo Paniagua Javier (gonzalo@ximian.com)
8 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
9 * Copyright 2004-2010 Novell, Inc (http://www.novell.com)
10 * Copyright 2001 Xamarin Inc (http://www.xamarin.com)
16 #include <mono/metadata/profiler-private.h>
17 #include <mono/metadata/threads.h>
18 #include <mono/metadata/threads-types.h>
19 #include <mono/metadata/threadpool-internals.h>
20 #include <mono/metadata/exception.h>
21 #include <mono/metadata/environment.h>
22 #include <mono/metadata/mono-config.h>
23 #include <mono/metadata/mono-mlist.h>
24 #include <mono/metadata/mono-perfcounters.h>
25 #include <mono/metadata/socket-io.h>
26 #include <mono/metadata/mono-cq.h>
27 #include <mono/metadata/mono-wsq.h>
28 #include <mono/metadata/mono-ptr-array.h>
29 #include <mono/metadata/object-internals.h>
30 #include <mono/io-layer/io-layer.h>
31 #include <mono/utils/mono-time.h>
32 #include <mono/utils/mono-proclib.h>
33 #include <mono/utils/mono-semaphore.h>
34 #include <mono/utils/atomic.h>
36 #ifdef HAVE_SYS_TIME_H
39 #include <sys/types.h>
46 #ifdef HAVE_SYS_SOCKET_H
47 #include <sys/socket.h>
49 #include <mono/utils/mono-poll.h>
51 #include <sys/epoll.h>
54 #include <sys/event.h>
58 #ifndef DISABLE_SOCKETS
59 #include "mono/io-layer/socket-wrappers.h"
62 #include "threadpool.h"
63 #include "threadpool-ms.h"
64 #include "threadpool-ms-io.h"
67 use_ms_threadpool (void)
69 static gboolean use_ms_tp = -1;
70 const gchar *mono_threadpool_env;
73 else if (!(mono_threadpool_env = g_getenv ("MONO_THREADPOOL")))
74 return use_ms_tp = FALSE;
75 else if (strcmp (mono_threadpool_env, "microsoft") == 0)
76 return use_ms_tp = TRUE;
78 return use_ms_tp = FALSE;
81 #define THREAD_WANTS_A_BREAK(t) ((t->state & (ThreadState_StopRequested | \
82 ThreadState_SuspendRequested)) != 0)
84 /* DEBUG: prints tp data every 2s */
87 /* mono_thread_pool_init called */
88 static volatile int tp_inited;
98 MONITOR_STATE_FALLING_ASLEEP,
99 MONITOR_STATE_SLEEPING
102 static SocketIOData socket_io_data;
106 MonoCQ *queue; /* GC root */
108 volatile gint waiting; /* threads waiting for a work item */
111 volatile gint pool_status; /* 0 -> not initialized, 1 -> initialized, 2 -> cleaning up */
112 /* min, max, n and busy -> Interlocked */
113 volatile gint min_threads;
114 volatile gint max_threads;
115 volatile gint nthreads;
116 volatile gint busy_threads;
118 void (*async_invoke) (gpointer data);
119 void *pc_nitems; /* Performance counter for total number of items in added */
120 void *pc_nthreads; /* Performance counter for total number of active threads */
122 volatile gint destroy_thread;
124 volatile gint32 njobs;
126 volatile gint32 nexecuted;
130 static ThreadPool async_tp;
131 static ThreadPool async_io_tp;
133 static void async_invoke_thread (gpointer data);
134 static MonoObject *mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares);
135 static void threadpool_free_queue (ThreadPool *tp);
136 static void threadpool_append_job (ThreadPool *tp, MonoObject *ar);
137 static void threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs);
138 static void threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer));
139 static void threadpool_start_idle_threads (ThreadPool *tp);
140 static void threadpool_kill_idle_threads (ThreadPool *tp);
141 static gboolean threadpool_start_thread (ThreadPool *tp);
142 static void threadpool_kill_thread (ThreadPool *tp);
143 static void monitor_thread (gpointer data);
144 static int get_event_from_state (MonoSocketAsyncResult *state);
146 static MonoClass *async_call_klass;
147 static MonoClass *socket_async_call_klass;
148 static MonoClass *process_async_call_klass;
150 static GPtrArray *threads;
151 mono_mutex_t threads_lock;
152 static GPtrArray *wsqs;
153 mono_mutex_t wsqs_lock;
154 static gboolean suspended;
156 static volatile gint32 monitor_njobs = 0;
157 static volatile gint32 monitor_state;
158 static MonoSemType monitor_sem;
159 static MonoInternalThread *monitor_internal_thread;
162 static MonoThreadPoolFunc tp_start_func;
163 static MonoThreadPoolFunc tp_finish_func;
164 static gpointer tp_hooks_user_data;
165 static MonoThreadPoolItemFunc tp_item_begin_func;
166 static MonoThreadPoolItemFunc tp_item_end_func;
167 static gpointer tp_item_user_data;
177 AIO_OP_RECV_JUST_CALLBACK,
178 AIO_OP_SEND_JUST_CALLBACK,
182 AIO_OP_ACCEPTRECEIVE,
183 AIO_OP_RECEIVE_BUFFERS,
188 // #include <mono/metadata/tpool-poll.c>
189 gpointer tp_poll_init (SocketIOData *data);
192 #include <mono/metadata/tpool-epoll.c>
193 #elif defined(USE_KQUEUE_FOR_THREADPOOL)
194 #include <mono/metadata/tpool-kqueue.c>
197 * Functions to check whenever a class is given system class. We need to cache things in MonoDomain since some of the
198 * assemblies can be unloaded.
202 is_system_type (MonoDomain *domain, MonoClass *klass)
204 if (domain->system_image == NULL)
205 domain->system_image = mono_image_loaded ("System");
207 return klass->image == domain->system_image;
211 is_corlib_type (MonoDomain *domain, MonoClass *klass)
213 return klass->image == mono_defaults.corlib;
216 #define check_type_cached(domain, ASSEMBLY, _class, _namespace, _name, loc) do { \
218 return *loc == _class; \
219 if (is_##ASSEMBLY##_type (domain, _class) && !strcmp (_name, _class->name) && !strcmp (_namespace, _class->name_space)) { \
226 #define check_corlib_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, corlib, _class, _namespace, _name, loc)
228 #define check_system_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, system, _class, _namespace, _name, loc)
231 is_corlib_asyncresult (MonoDomain *domain, MonoClass *klass)
233 check_corlib_type_cached (domain, klass, "System.Runtime.Remoting.Messaging", "AsyncResult", &domain->corlib_asyncresult_class);
237 is_socketasyncresult (MonoDomain *domain, MonoClass *klass)
239 static MonoClass *socket_async_result_klass = NULL;
240 check_system_type_cached (domain, klass, "System.Net.Sockets", "SocketAsyncResult", &socket_async_result_klass);
244 is_socketasynccall (MonoDomain *domain, MonoClass *klass)
246 static MonoClass *socket_async_callback_klass = NULL;
247 check_system_type_cached (domain, klass, "System.Net.Sockets", "SocketAsyncCallback", &socket_async_callback_klass);
251 is_appdomainunloaded_exception (MonoDomain *domain, MonoClass *klass)
253 check_corlib_type_cached (domain, klass, "System", "AppDomainUnloadedException", &domain->ad_unloaded_ex_class);
257 is_sd_process (MonoDomain *domain, MonoClass *klass)
259 check_system_type_cached (domain, klass, "System.Diagnostics", "Process", &domain->process_class);
263 is_sdp_asyncreadhandler (MonoDomain *domain, MonoClass *klass)
266 return (klass->nested_in &&
267 is_sd_process (domain, klass->nested_in) &&
268 !strcmp (klass->name, "AsyncReadHandler"));
272 #ifdef DISABLE_SOCKETS
275 socket_io_cleanup (SocketIOData *data)
280 get_event_from_state (MonoSocketAsyncResult *state)
282 g_assert_not_reached ();
287 get_events_from_list (MonoMList *list)
295 socket_io_cleanup (SocketIOData *data)
297 mono_mutex_lock (&data->io_lock);
298 if (data->inited != 2) {
299 mono_mutex_unlock (&data->io_lock);
303 data->shutdown (data->event_data);
304 mono_mutex_unlock (&data->io_lock);
308 get_event_from_state (MonoSocketAsyncResult *state)
310 switch (state->operation) {
313 case AIO_OP_RECV_JUST_CALLBACK:
314 case AIO_OP_RECEIVEFROM:
315 case AIO_OP_READPIPE:
316 case AIO_OP_ACCEPTRECEIVE:
317 case AIO_OP_RECEIVE_BUFFERS:
320 case AIO_OP_SEND_JUST_CALLBACK:
323 case AIO_OP_SEND_BUFFERS:
324 case AIO_OP_DISCONNECT:
326 default: /* Should never happen */
327 g_message ("get_event_from_state: unknown value in switch!!!");
333 get_events_from_list (MonoMList *list)
335 MonoSocketAsyncResult *state;
338 while (list && (state = (MonoSocketAsyncResult *)mono_mlist_get_data (list))) {
339 events |= get_event_from_state (state);
340 list = mono_mlist_next (list);
346 #define ICALL_RECV(x) ves_icall_System_Net_Sockets_Socket_Receive_internal (\
347 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
348 x->socket_flags, &x->error);
350 #define ICALL_SEND(x) ves_icall_System_Net_Sockets_Socket_Send_internal (\
351 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
352 x->socket_flags, &x->error);
354 #endif /* !DISABLE_SOCKETS */
357 threadpool_jobs_inc (MonoObject *obj)
360 InterlockedIncrement (&obj->vtable->domain->threadpool_jobs);
364 threadpool_jobs_dec (MonoObject *obj)
372 domain = obj->vtable->domain;
373 remaining_jobs = InterlockedDecrement (&domain->threadpool_jobs);
374 if (remaining_jobs == 0 && domain->cleanup_semaphore) {
375 ReleaseSemaphore (domain->cleanup_semaphore, 1, NULL);
382 get_io_event (MonoMList **list, gint event)
392 state = mono_mlist_get_data (current);
393 if (get_event_from_state ((MonoSocketAsyncResult *) state) == event)
398 current = mono_mlist_next (current);
403 mono_mlist_set_next (prev, mono_mlist_next (current));
405 *list = mono_mlist_next (*list);
413 * select/poll wake up when a socket is closed, but epoll just removes
414 * the socket from its internal list without notification.
417 mono_thread_pool_remove_socket (int sock)
420 MonoSocketAsyncResult *state;
423 if (use_ms_threadpool ()) {
424 #ifndef DISABLE_SOCKETS
425 mono_threadpool_ms_io_remove_socket (sock);
430 if (socket_io_data.inited == 0)
433 mono_mutex_lock (&socket_io_data.io_lock);
434 if (socket_io_data.sock_to_state == NULL) {
435 mono_mutex_unlock (&socket_io_data.io_lock);
438 list = mono_g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
440 mono_g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
441 mono_mutex_unlock (&socket_io_data.io_lock);
444 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
445 if (state->operation == AIO_OP_RECEIVE)
446 state->operation = AIO_OP_RECV_JUST_CALLBACK;
447 else if (state->operation == AIO_OP_SEND)
448 state->operation = AIO_OP_SEND_JUST_CALLBACK;
450 ares = get_io_event (&list, MONO_POLLIN);
451 threadpool_append_job (&async_io_tp, ares);
453 ares = get_io_event (&list, MONO_POLLOUT);
454 threadpool_append_job (&async_io_tp, ares);
460 init_event_system (SocketIOData *data)
463 if (data->event_system == EPOLL_BACKEND) {
464 data->event_data = tp_epoll_init (data);
465 if (data->event_data == NULL) {
466 if (g_getenv ("MONO_DEBUG"))
467 g_message ("Falling back to poll()");
468 data->event_system = POLL_BACKEND;
471 #elif defined(USE_KQUEUE_FOR_THREADPOOL)
472 if (data->event_system == KQUEUE_BACKEND)
473 data->event_data = tp_kqueue_init (data);
475 if (data->event_system == POLL_BACKEND)
476 data->event_data = tp_poll_init (data);
480 socket_io_init (SocketIOData *data)
484 if (data->inited >= 2) // 2 -> initialized, 3-> cleaned up
487 inited = InterlockedCompareExchange (&data->inited, 1, 0);
490 if (data->inited >= 2)
496 mono_mutex_lock (&data->io_lock);
497 data->sock_to_state = mono_g_hash_table_new_type (g_direct_hash, g_direct_equal, MONO_HASH_VALUE_GC);
499 data->event_system = EPOLL_BACKEND;
500 #elif defined(USE_KQUEUE_FOR_THREADPOOL)
501 data->event_system = KQUEUE_BACKEND;
503 data->event_system = POLL_BACKEND;
505 if (g_getenv ("MONO_DISABLE_AIO") != NULL)
506 data->event_system = POLL_BACKEND;
508 init_event_system (data);
509 mono_thread_create_internal (mono_get_root_domain (), data->wait, data, TRUE, SMALL_STACK);
510 mono_mutex_unlock (&data->io_lock);
512 threadpool_start_thread (&async_io_tp);
516 socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
519 SocketIOData *data = &socket_io_data;
524 socket_io_init (&socket_io_data);
525 if (mono_runtime_is_shutting_down () || data->inited == 3 || data->sock_to_state == NULL)
527 if (async_tp.pool_status == 2)
530 MONO_OBJECT_SETREF (state, ares, ares);
532 fd = GPOINTER_TO_INT (state->handle);
533 mono_mutex_lock (&data->io_lock);
534 if (data->sock_to_state == NULL) {
535 mono_mutex_unlock (&data->io_lock);
538 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
540 list = mono_mlist_alloc ((MonoObject*)state);
543 list = mono_mlist_append (list, (MonoObject*)state);
547 mono_g_hash_table_replace (data->sock_to_state, state->handle, list);
548 ievt = get_events_from_list (list);
549 /* The modify function leaves the io_lock critical section. */
550 data->modify (data, fd, state->operation, ievt, is_new);
553 #ifndef DISABLE_SOCKETS
555 socket_io_filter (MonoObject *target, MonoObject *state)
558 MonoSocketAsyncResult *sock_res;
562 if (target == NULL || state == NULL)
565 domain = target->vtable->domain;
566 klass = target->vtable->klass;
567 if (socket_async_call_klass == NULL && is_socketasynccall (domain, klass))
568 socket_async_call_klass = klass;
570 if (process_async_call_klass == NULL && is_sdp_asyncreadhandler (domain, klass))
571 process_async_call_klass = klass;
573 if (klass != socket_async_call_klass && klass != process_async_call_klass)
576 sock_res = (MonoSocketAsyncResult *) state;
577 op = sock_res->operation;
578 if (op < AIO_OP_FIRST || op >= AIO_OP_LAST)
583 #endif /* !DISABLE_SOCKETS */
585 /* Returns the exception thrown when invoking, if any */
587 mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares)
589 MonoObject *exc = NULL;
591 mono_async_result_invoke (ares, &exc);
594 InterlockedDecrement (&tp->njobs);
597 InterlockedIncrement (&tp->nexecuted);
599 if (InterlockedDecrement (&monitor_njobs) == 0)
600 monitor_state = MONITOR_STATE_FALLING_ASLEEP;
606 threadpool_start_idle_threads (ThreadPool *tp)
611 stack_size = (!tp->is_io) ? 0 : SMALL_STACK;
615 if (n >= tp->min_threads)
617 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n)
620 #ifndef DISABLE_PERFCOUNTERS
621 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
623 mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE, stack_size);
629 threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer))
631 memset (tp, 0, sizeof (ThreadPool));
632 tp->min_threads = min_threads;
633 tp->max_threads = max_threads;
634 tp->async_invoke = async_invoke;
635 tp->queue = mono_cq_create ();
636 MONO_SEM_INIT (&tp->new_job, 0);
639 #ifndef DISABLE_PERFCOUNTERS
641 init_perf_counter (const char *category, const char *counter)
643 MonoString *category_str;
644 MonoString *counter_str;
650 if (category == NULL || counter == NULL)
652 root = mono_get_root_domain ();
653 category_str = mono_string_new (root, category);
654 counter_str = mono_string_new (root, counter);
655 machine = mono_string_new (root, ".");
656 return mono_perfcounter_get_impl (category_str, counter_str, NULL, machine, &type, &custom);
662 print_pool_info (ThreadPool *tp)
665 // if (tp->tail - tp->head == 0)
668 g_print ("Pool status? %d\n", InterlockedCompareExchange (&tp->pool_status, 0, 0));
669 g_print ("Min. threads: %d\n", InterlockedCompareExchange (&tp->min_threads, 0, 0));
670 g_print ("Max. threads: %d\n", InterlockedCompareExchange (&tp->max_threads, 0, 0));
671 g_print ("nthreads: %d\n", InterlockedCompareExchange (&tp->nthreads, 0, 0));
672 g_print ("busy threads: %d\n", InterlockedCompareExchange (&tp->busy_threads, 0, 0));
673 g_print ("Waiting: %d\n", InterlockedCompareExchange (&tp->waiting, 0, 0));
674 g_print ("Queued: %d\n", (tp->tail - tp->head));
675 if (tp == &async_tp) {
677 mono_mutex_lock (&wsqs_lock);
678 for (i = 0; i < wsqs->len; i++) {
679 g_print ("\tWSQ %d: %d\n", i, mono_wsq_count (g_ptr_array_index (wsqs, i)));
681 mono_mutex_unlock (&wsqs_lock);
683 g_print ("\tSockets: %d\n", mono_g_hash_table_size (socket_io_data.sock_to_state));
685 g_print ("-------------\n");
689 signal_handler (int signo)
694 g_print ("\n-----Non-IO-----\n");
695 print_pool_info (tp);
697 g_print ("\n-----IO-----\n");
698 print_pool_info (tp);
703 #define SAMPLES_PERIOD 500
704 #define HISTORY_SIZE 10
705 /* number of iteration without any jobs
706 in the queue before going to sleep */
707 #define NUM_WAITING_ITERATIONS 10
717 * - 1 if the number of threads should increase
718 * - 0 if it should not change
719 * - -1 if it should decrease
720 * - -2 in case of error
723 monitor_heuristic (gint16 *current, gint16 *history_size, SamplesHistory *history, ThreadPool *tp)
726 gint8 decision G_GNUC_UNUSED;
728 gboolean all_waitsleepjoin;
729 MonoInternalThread *thread;
732 * The following heuristic tries to approach the optimal number of threads to maximize jobs throughput. To
733 * achieve this, it simply stores the number of jobs executed (nexecuted), the number of Threads (nthreads)
734 * and the decision (nthreads_diff) for the past HISTORY_SIZE periods of time, each period being of
735 * duration SAMPLES_PERIOD ms. This history gives us an insight into what happened, and to see if we should
736 * increase or reduce the number of threads by comparing the last period (current) to the best one.
738 * The algorithm can be describe as following :
739 * - if we have a better throughput than the best period : we should either increase the number of threads
740 * in case we already have more threads, either reduce the number of threads if we have less threads; this
741 * is equivalent to move away from the number of threads of the best period, because we are currently better
742 * - if we have a worse throughput than the best period : we should either decrease the number of threads if
743 * we have more threads, either increase the number of threads if we have less threads; this is equivalent
744 * to get closer to the number of threads of the best period, because we are currently worse
747 *history_size = MIN (*history_size + 1, HISTORY_SIZE);
748 cur = *current = (*current + 1) % *history_size;
750 history [cur].nthreads = tp->nthreads;
751 history [cur].nexecuted = InterlockedExchange (&tp->nexecuted, 0);
754 /* if we have waiting thread in the pool, then do not create a new one */
755 history [cur].nthreads_diff = tp->waiting > 1 ? -1 : 0;
757 } else if (tp->nthreads < tp->min_threads) {
758 history [cur].nthreads_diff = 1;
760 } else if (*history_size <= 1) {
761 /* first iteration, let's add a thread by default */
762 history [cur].nthreads_diff = 1;
765 mono_mutex_lock (&threads_lock);
766 if (threads == NULL) {
767 mono_mutex_unlock (&threads_lock);
770 all_waitsleepjoin = TRUE;
771 for (i = 0; i < threads->len; ++i) {
772 thread = g_ptr_array_index (threads, i);
773 if (!(thread->state & ThreadState_WaitSleepJoin)) {
774 all_waitsleepjoin = FALSE;
778 mono_mutex_unlock (&threads_lock);
780 if (all_waitsleepjoin) {
781 /* we might be in a condition of starvation/deadlock with tasks waiting for each others */
782 history [cur].nthreads_diff = 1;
785 max = cur == 0 ? 1 : 0;
786 for (i = 0; i < *history_size; i++) {
789 if (history [i].nexecuted > history [max].nexecuted)
793 if (history [cur].nexecuted >= history [max].nexecuted) {
794 /* we improved the situation, let's continue ! */
795 history [cur].nthreads_diff = history [cur].nthreads >= history [max].nthreads ? 1 : -1;
798 /* we made it worse, let's return to previous situation */
799 history [cur].nthreads_diff = history [cur].nthreads >= history [max].nthreads ? -1 : 1;
806 printf ("monitor_thread: decision: %1d, history [current]: {nexecuted: %5d, nthreads: %3d, waiting: %2d, nthreads_diff: %2d}, history [max]: {nexecuted: %5d, nthreads: %3d}\n",
807 decision, history [cur].nexecuted, history [cur].nthreads, tp->waiting, history [cur].nthreads_diff, history [max].nexecuted, history [max].nthreads);
810 return history [cur].nthreads_diff;
814 monitor_thread (gpointer unused)
816 ThreadPool *pools [2];
817 MonoInternalThread *thread;
821 gint8 num_waiting_iterations = 0;
823 gint16 history_size = 0, current = -1;
824 SamplesHistory *history = malloc (sizeof (SamplesHistory) * HISTORY_SIZE);
826 pools [0] = &async_tp;
827 pools [1] = &async_io_tp;
828 thread = mono_thread_internal_current ();
829 ves_icall_System_Threading_Thread_SetName_internal (thread, mono_string_new (mono_domain_get (), "Threadpool monitor"));
832 i = 10; //number of spurious awakes we tolerate before doing a round of rebalancing.
833 mono_gc_set_skip_thread (TRUE);
834 MONO_PREPARE_BLOCKING
837 ts = mono_msec_ticks ();
838 if (SleepEx (ms, TRUE) == 0)
840 ms -= (mono_msec_ticks () - ts);
841 if (mono_runtime_is_shutting_down ())
843 check_for_interruption_critical ();
844 } while (ms > 0 && i--);
846 mono_gc_set_skip_thread (FALSE);
848 if (mono_runtime_is_shutting_down ())
854 /* threadpool is cleaning up */
855 if (async_tp.pool_status == 2 || async_io_tp.pool_status == 2)
858 MONO_PREPARE_BLOCKING
859 switch (monitor_state) {
860 case MONITOR_STATE_AWAKE:
861 num_waiting_iterations = 0;
863 case MONITOR_STATE_FALLING_ASLEEP:
864 if (++num_waiting_iterations == NUM_WAITING_ITERATIONS) {
865 if (monitor_state == MONITOR_STATE_FALLING_ASLEEP && InterlockedCompareExchange (&monitor_state, MONITOR_STATE_SLEEPING, MONITOR_STATE_FALLING_ASLEEP) == MONITOR_STATE_FALLING_ASLEEP) {
866 MONO_SEM_WAIT (&monitor_sem);
868 num_waiting_iterations = 0;
874 case MONITOR_STATE_SLEEPING:
875 g_assert_not_reached ();
879 for (i = 0; i < 2; i++) {
884 if (!tp->waiting && mono_cq_count (tp->queue) > 0)
885 threadpool_start_thread (tp);
887 gint8 nthreads_diff = monitor_heuristic (¤t, &history_size, history, tp);
889 if (nthreads_diff == 1)
890 threadpool_start_thread (tp);
891 else if (nthreads_diff == -1)
892 threadpool_kill_thread (tp);
899 mono_thread_pool_init_tls (void)
901 if (use_ms_threadpool ()) {
902 mono_threadpool_ms_init_tls ();
910 mono_thread_pool_init (void)
912 gint threads_per_cpu = 1;
917 if (use_ms_threadpool ()) {
918 mono_threadpool_ms_init ();
922 cpu_count = mono_cpu_count ();
927 result = InterlockedCompareExchange (&tp_inited, 1, 0);
936 MONO_GC_REGISTER_ROOT_FIXED (socket_io_data.sock_to_state);
937 mono_mutex_init_recursive (&socket_io_data.io_lock);
938 if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
939 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
940 if (threads_per_cpu < 1)
944 thread_count = MIN (cpu_count * threads_per_cpu, 100 * cpu_count);
945 threadpool_init (&async_tp, thread_count, MAX (100 * cpu_count, thread_count), async_invoke_thread);
946 threadpool_init (&async_io_tp, cpu_count * 2, cpu_count * 4, async_invoke_thread);
947 async_io_tp.is_io = TRUE;
949 async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
950 g_assert (async_call_klass);
952 mono_mutex_init (&threads_lock);
953 threads = g_ptr_array_sized_new (thread_count);
956 mono_mutex_init_recursive (&wsqs_lock);
957 wsqs = g_ptr_array_sized_new (MAX (100 * cpu_count, thread_count));
959 #ifndef DISABLE_PERFCOUNTERS
960 async_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "Work Items Added");
961 g_assert (async_tp.pc_nitems);
963 async_io_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "IO Work Items Added");
964 g_assert (async_io_tp.pc_nitems);
966 async_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of Threads");
967 g_assert (async_tp.pc_nthreads);
969 async_io_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of IO Threads");
970 g_assert (async_io_tp.pc_nthreads);
974 signal (SIGALRM, signal_handler);
978 MONO_SEM_INIT (&monitor_sem, 0);
979 monitor_state = MONITOR_STATE_AWAKE;
983 static MonoAsyncResult *
984 create_simple_asyncresult (MonoObject *target, MonoObject *state)
986 MonoDomain *domain = mono_domain_get ();
987 MonoAsyncResult *ares;
989 /* Don't call mono_async_result_new() to avoid capturing the context */
990 ares = (MonoAsyncResult *) mono_object_new (domain, mono_defaults.asyncresult_class);
991 MONO_OBJECT_SETREF (ares, async_delegate, target);
992 MONO_OBJECT_SETREF (ares, async_state, state);
997 icall_append_io_job (MonoObject *target, MonoSocketAsyncResult *state)
999 MonoAsyncResult *ares;
1001 ares = create_simple_asyncresult (target, (MonoObject *) state);
1003 if (use_ms_threadpool ()) {
1004 #ifndef DISABLE_SOCKETS
1005 mono_threadpool_ms_io_add (ares, state);
1010 socket_io_add (ares, state);
1014 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
1018 MonoAsyncResult *ares;
1021 if (use_ms_threadpool ())
1022 return mono_threadpool_ms_add (target, msg, async_callback, state);
1024 domain = mono_domain_get ();
1026 ac = (MonoAsyncCall*)mono_object_new (domain, async_call_klass);
1027 MONO_OBJECT_SETREF (ac, msg, msg);
1028 MONO_OBJECT_SETREF (ac, state, state);
1030 if (async_callback) {
1031 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
1032 MONO_OBJECT_SETREF (ac, cb_target, async_callback);
1035 ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
1036 MONO_OBJECT_SETREF (ares, async_delegate, target);
1038 #ifndef DISABLE_SOCKETS
1039 if (socket_io_filter (target, state)) {
1040 socket_io_add (ares, (MonoSocketAsyncResult *) state);
1044 threadpool_append_job (&async_tp, (MonoObject *) ares);
1049 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1054 if (use_ms_threadpool ()) {
1055 return mono_threadpool_ms_finish (ares, out_args, exc);
1061 /* check if already finished */
1062 mono_monitor_enter ((MonoObject *) ares);
1064 if (ares->endinvoke_called) {
1065 *exc = (MonoObject *) mono_get_exception_invalid_operation (NULL);
1066 mono_monitor_exit ((MonoObject *) ares);
1070 ares->endinvoke_called = 1;
1071 /* wait until we are really finished */
1072 if (!ares->completed) {
1073 if (ares->handle == NULL) {
1074 wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1075 g_assert(wait_event != 0);
1076 MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), wait_event));
1078 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
1080 mono_monitor_exit ((MonoObject *) ares);
1081 MONO_PREPARE_BLOCKING
1082 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
1083 MONO_FINISH_BLOCKING
1085 mono_monitor_exit ((MonoObject *) ares);
1088 ac = (MonoAsyncCall *) ares->object_data;
1089 g_assert (ac != NULL);
1090 *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1091 *out_args = ac->out_args;
1097 threadpool_kill_idle_threads (ThreadPool *tp)
1101 n = (gint) InterlockedCompareExchange (&tp->max_threads, 0, -1);
1104 MONO_SEM_POST (&tp->new_job);
1109 mono_thread_pool_cleanup (void)
1111 if (use_ms_threadpool ()) {
1112 mono_threadpool_ms_cleanup ();
1116 if (InterlockedExchange (&async_io_tp.pool_status, 2) == 1) {
1117 socket_io_cleanup (&socket_io_data); /* Empty when DISABLE_SOCKETS is defined */
1118 threadpool_kill_idle_threads (&async_io_tp);
1121 if (async_io_tp.queue != NULL) {
1122 MONO_SEM_DESTROY (&async_io_tp.new_job);
1123 threadpool_free_queue (&async_io_tp);
1127 if (InterlockedExchange (&async_tp.pool_status, 2) == 1) {
1128 threadpool_kill_idle_threads (&async_tp);
1129 threadpool_free_queue (&async_tp);
1133 mono_mutex_lock (&threads_lock);
1135 g_ptr_array_free (threads, FALSE);
1137 mono_mutex_unlock (&threads_lock);
1141 mono_mutex_lock (&wsqs_lock);
1142 mono_wsq_cleanup ();
1144 g_ptr_array_free (wsqs, TRUE);
1146 mono_mutex_unlock (&wsqs_lock);
1147 MONO_SEM_DESTROY (&async_tp.new_job);
1150 MONO_SEM_DESTROY (&monitor_sem);
1154 threadpool_start_thread (ThreadPool *tp)
1158 MonoInternalThread *thread;
1160 stack_size = (!tp->is_io) ? 0 : SMALL_STACK;
1161 while (!mono_runtime_is_shutting_down () && (n = tp->nthreads) < tp->max_threads) {
1162 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n) {
1163 #ifndef DISABLE_PERFCOUNTERS
1164 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
1167 thread = mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE, stack_size);
1169 mono_mutex_lock (&threads_lock);
1170 thread = mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE, stack_size);
1171 g_assert (threads != NULL);
1172 g_ptr_array_add (threads, thread);
1173 mono_mutex_unlock (&threads_lock);
1183 pulse_on_new_job (ThreadPool *tp)
1186 MONO_SEM_POST (&tp->new_job);
1190 threadpool_kill_thread (ThreadPool *tp)
1192 if (tp->destroy_thread == 0 && InterlockedCompareExchange (&tp->destroy_thread, 1, 0) == 0)
1193 pulse_on_new_job (tp);
1197 icall_append_job (MonoObject *ar)
1199 threadpool_append_jobs (&async_tp, &ar, 1);
1203 threadpool_append_job (ThreadPool *tp, MonoObject *ar)
1205 threadpool_append_jobs (tp, &ar, 1);
1209 threadpool_append_async_io_jobs (MonoObject **jobs, gint njobs)
1211 threadpool_append_jobs (&async_io_tp, jobs, njobs);
1215 threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs)
1220 if (mono_runtime_is_shutting_down ())
1223 if (tp->pool_status == 0 && InterlockedCompareExchange (&tp->pool_status, 1, 0) == 0) {
1225 monitor_internal_thread = mono_thread_create_internal (mono_get_root_domain (), monitor_thread, NULL, TRUE, SMALL_STACK);
1226 monitor_internal_thread->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
1227 threadpool_start_thread (tp);
1229 /* Create on demand up to min_threads to avoid startup penalty for apps that don't use
1230 * the threadpool that much
1232 if (mono_config_is_server_mode ()) {
1233 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, tp, TRUE, SMALL_STACK);
1237 InterlockedAdd (&monitor_njobs, njobs);
1239 if (monitor_state == MONITOR_STATE_SLEEPING && InterlockedCompareExchange (&monitor_state, MONITOR_STATE_AWAKE, MONITOR_STATE_SLEEPING) == MONITOR_STATE_SLEEPING)
1240 MONO_SEM_POST (&monitor_sem);
1242 if (monitor_state == MONITOR_STATE_FALLING_ASLEEP)
1243 InterlockedCompareExchange (&monitor_state, MONITOR_STATE_AWAKE, MONITOR_STATE_FALLING_ASLEEP);
1245 for (i = 0; i < njobs; i++) {
1247 if (ar == NULL || mono_domain_is_unloading (ar->vtable->domain))
1248 continue; /* Might happen when cleaning domain jobs */
1249 threadpool_jobs_inc (ar);
1250 #ifndef DISABLE_PERFCOUNTERS
1251 mono_perfcounter_update_value (tp->pc_nitems, TRUE, 1);
1253 if (!tp->is_io && mono_wsq_local_push (ar))
1256 mono_cq_enqueue (tp->queue, ar);
1260 InterlockedAdd (&tp->njobs, njobs);
1263 for (i = 0; tp->waiting > 0 && i < MIN(njobs, tp->max_threads); i++)
1264 pulse_on_new_job (tp);
1268 threadpool_clear_queue (ThreadPool *tp, MonoDomain *domain)
1271 MonoMList *other = NULL;
1272 MonoCQ *queue = tp->queue;
1277 while (mono_cq_dequeue (queue, &obj)) {
1280 if (obj->vtable->domain != domain)
1281 other = mono_mlist_prepend (other, obj);
1282 threadpool_jobs_dec (obj);
1285 if (mono_runtime_is_shutting_down ())
1289 threadpool_append_job (tp, (MonoObject *) mono_mlist_get_data (other));
1290 other = mono_mlist_next (other);
1295 remove_sockstate_for_domain (gpointer key, gpointer value, gpointer user_data)
1297 MonoMList *list = value;
1298 gboolean remove = FALSE;
1300 MonoObject *data = mono_mlist_get_data (list);
1301 if (mono_object_domain (data) == user_data) {
1303 mono_mlist_set_data (list, NULL);
1305 list = mono_mlist_next (list);
1307 //FIXME is there some sort of additional unregistration we need to perform here?
1312 * Clean up the threadpool of all domain jobs.
1313 * Can only be called as part of the domain unloading process as
1314 * it will wait for all jobs to be visible to the interruption code.
1317 mono_thread_pool_remove_domain_jobs (MonoDomain *domain, int timeout)
1323 if (use_ms_threadpool ()) {
1324 return mono_threadpool_ms_remove_domain_jobs (domain, timeout);
1330 g_assert (domain->state == MONO_APPDOMAIN_UNLOADING);
1332 threadpool_clear_queue (&async_tp, domain);
1333 threadpool_clear_queue (&async_io_tp, domain);
1335 mono_mutex_lock (&socket_io_data.io_lock);
1336 if (socket_io_data.sock_to_state)
1337 mono_g_hash_table_foreach_remove (socket_io_data.sock_to_state, remove_sockstate_for_domain, domain);
1339 mono_mutex_unlock (&socket_io_data.io_lock);
1342 * There might be some threads out that could be about to execute stuff from the given domain.
1343 * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
1345 sem_handle = CreateSemaphore (NULL, 0, 1, NULL);
1347 domain->cleanup_semaphore = sem_handle;
1349 * The memory barrier here is required to have global ordering between assigning to cleanup_semaphone
1350 * and reading threadpool_jobs.
1351 * Otherwise this thread could read a stale version of threadpool_jobs and wait forever.
1353 mono_memory_write_barrier ();
1355 if (domain->threadpool_jobs && timeout != -1)
1356 start_time = mono_msec_ticks ();
1357 while (domain->threadpool_jobs) {
1358 MONO_PREPARE_BLOCKING
1359 WaitForSingleObject (sem_handle, timeout);
1360 MONO_FINISH_BLOCKING
1361 if (timeout != -1 && (mono_msec_ticks () - start_time) > timeout) {
1367 domain->cleanup_semaphore = NULL;
1368 CloseHandle (sem_handle);
1373 threadpool_free_queue (ThreadPool *tp)
1375 mono_cq_destroy (tp->queue);
1380 mono_thread_pool_is_queue_array (MonoArray *o)
1382 if (use_ms_threadpool ()) {
1383 return mono_threadpool_ms_is_queue_array (o);
1386 // gpointer obj = o;
1388 // FIXME: need some fix in sgen code.
1398 mono_mutex_lock (&wsqs_lock);
1399 wsq = mono_wsq_create ();
1401 mono_mutex_unlock (&wsqs_lock);
1404 for (i = 0; i < wsqs->len; i++) {
1405 if (g_ptr_array_index (wsqs, i) == NULL) {
1406 wsqs->pdata [i] = wsq;
1407 mono_mutex_unlock (&wsqs_lock);
1411 g_ptr_array_add (wsqs, wsq);
1412 mono_mutex_unlock (&wsqs_lock);
1417 remove_wsq (MonoWSQ *wsq)
1424 mono_mutex_lock (&wsqs_lock);
1426 mono_mutex_unlock (&wsqs_lock);
1429 g_ptr_array_remove_fast (wsqs, wsq);
1432 * Only clean this up when shutting down, any other case will error out
1433 * if we're removing a queue that still has work items.
1435 if (mono_runtime_is_shutting_down ()) {
1436 while (mono_wsq_local_pop (&data)) {
1437 threadpool_jobs_dec (data);
1441 mono_wsq_destroy (wsq);
1442 mono_mutex_unlock (&wsqs_lock);
1446 try_steal (MonoWSQ *local_wsq, gpointer *data, gboolean retry)
1451 if (wsqs == NULL || data == NULL || *data != NULL)
1456 if (mono_runtime_is_shutting_down ())
1459 MONO_PREPARE_BLOCKING
1460 mono_mutex_lock (&wsqs_lock);
1461 MONO_FINISH_BLOCKING
1462 for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
1465 wsq = wsqs->pdata [i];
1466 if (wsq == local_wsq || mono_wsq_count (wsq) == 0)
1468 mono_wsq_try_steal (wsqs->pdata [i], data, ms);
1469 if (*data != NULL) {
1470 mono_mutex_unlock (&wsqs_lock);
1474 mono_mutex_unlock (&wsqs_lock);
1476 } while (retry && ms < 11);
1480 dequeue_or_steal (ThreadPool *tp, gpointer *data, MonoWSQ *local_wsq)
1482 MonoCQ *queue = tp->queue;
1483 if (mono_runtime_is_shutting_down () || !queue)
1485 mono_cq_dequeue (queue, (MonoObject **) data);
1486 if (!tp->is_io && !*data)
1487 try_steal (local_wsq, data, FALSE);
1488 return (*data != NULL);
1492 should_i_die (ThreadPool *tp)
1494 gboolean result = FALSE;
1495 if (tp->destroy_thread == 1 && InterlockedCompareExchange (&tp->destroy_thread, 0, 1) == 1)
1496 result = (tp->nthreads > tp->min_threads);
1501 set_tp_thread_info (ThreadPool *tp)
1504 MonoInternalThread *thread = mono_thread_internal_current ();
1506 mono_profiler_thread_start (thread->tid);
1507 name = (tp->is_io) ? "IO Threadpool worker" : "Threadpool worker";
1508 mono_thread_set_name_internal (thread, mono_string_new (mono_domain_get (), name), FALSE);
1512 clear_thread_state (void)
1514 MonoInternalThread *thread = mono_thread_internal_current ();
1515 /* If the callee changes the background status, set it back to TRUE */
1516 mono_thread_clr_state (thread , ~ThreadState_Background);
1517 if (!mono_thread_test_state (thread , ThreadState_Background))
1518 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
1522 check_for_interruption_critical (void)
1524 MonoInternalThread *thread;
1525 /*RULE NUMBER ONE OF SKIP_THREAD: NEVER POKE MANAGED STATE.*/
1526 mono_gc_set_skip_thread (FALSE);
1528 thread = mono_thread_internal_current ();
1529 if (THREAD_WANTS_A_BREAK (thread))
1530 mono_thread_interruption_checkpoint ();
1532 /*RULE NUMBER TWO OF SKIP_THREAD: READ RULE NUMBER ONE.*/
1533 mono_gc_set_skip_thread (TRUE);
1537 fire_profiler_thread_end (void)
1539 MonoInternalThread *thread = mono_thread_internal_current ();
1540 mono_profiler_thread_end (thread->tid);
1544 async_invoke_thread (gpointer data)
1556 set_tp_thread_info (tp);
1559 tp_start_func (tp_hooks_user_data);
1563 MonoAsyncResult *ar;
1565 gboolean is_io_task;
1570 ar = (MonoAsyncResult *) data;
1572 InterlockedIncrement (&tp->busy_threads);
1573 domain = ((MonoObject *)ar)->vtable->domain;
1574 #ifndef DISABLE_SOCKETS
1575 klass = ((MonoObject *) data)->vtable->klass;
1576 is_io_task = !is_corlib_asyncresult (domain, klass);
1579 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1580 is_socket = is_socketasyncresult (domain, klass);
1582 switch (state->operation) {
1583 case AIO_OP_RECEIVE:
1584 state->total = ICALL_RECV (state);
1587 state->total = ICALL_SEND (state);
1592 /* worker threads invokes methods in different domains,
1593 * so we need to set the right domain here */
1596 if (mono_domain_is_unloading (domain) || mono_runtime_is_shutting_down ()) {
1597 threadpool_jobs_dec ((MonoObject *)ar);
1600 InterlockedDecrement (&tp->busy_threads);
1602 mono_thread_push_appdomain_ref (domain);
1603 if (threadpool_jobs_dec ((MonoObject *)ar)) {
1606 mono_thread_pop_appdomain_ref ();
1607 InterlockedDecrement (&tp->busy_threads);
1611 if (mono_domain_set (domain, FALSE)) {
1614 if (tp_item_begin_func)
1615 tp_item_begin_func (tp_item_user_data);
1617 exc = mono_async_invoke (tp, ar);
1618 if (tp_item_end_func)
1619 tp_item_end_func (tp_item_user_data);
1621 mono_internal_thread_unhandled_exception (exc);
1622 if (is_socket && tp->is_io) {
1623 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1625 if (state->completed && state->callback) {
1626 MonoAsyncResult *cb_ares;
1627 cb_ares = create_simple_asyncresult ((MonoObject *) state->callback,
1628 (MonoObject *) state);
1629 icall_append_job ((MonoObject *) cb_ares);
1632 mono_domain_set (mono_get_root_domain (), TRUE);
1634 mono_thread_pop_appdomain_ref ();
1635 InterlockedDecrement (&tp->busy_threads);
1636 clear_thread_state ();
1642 must_die = should_i_die (tp);
1644 mono_wsq_suspend (wsq);
1646 if (tp->is_io || !mono_wsq_local_pop (&data))
1647 dequeue_or_steal (tp, &data, wsq);
1651 while (!must_die && !data && n_naps < 4) {
1654 InterlockedIncrement (&tp->waiting);
1656 // Another thread may have added a job into its wsq since the last call to dequeue_or_steal
1657 // Check all the queues again before entering the wait loop
1658 dequeue_or_steal (tp, &data, wsq);
1660 InterlockedDecrement (&tp->waiting);
1664 mono_gc_set_skip_thread (TRUE);
1665 MONO_PREPARE_BLOCKING
1667 #if defined(__OpenBSD__)
1668 while (mono_cq_count (tp->queue) == 0 && (res = mono_sem_wait (&tp->new_job, TRUE)) == -1) {// && errno == EINTR) {
1670 while (mono_cq_count (tp->queue) == 0 && (res = mono_sem_timedwait (&tp->new_job, 2000, TRUE)) == -1) {// && errno == EINTR) {
1672 if (mono_runtime_is_shutting_down ())
1674 check_for_interruption_critical ();
1676 InterlockedDecrement (&tp->waiting);
1678 MONO_FINISH_BLOCKING
1679 mono_gc_set_skip_thread (FALSE);
1681 if (mono_runtime_is_shutting_down ())
1683 must_die = should_i_die (tp);
1684 dequeue_or_steal (tp, &data, wsq);
1688 if (!data && !tp->is_io && !mono_runtime_is_shutting_down ()) {
1689 mono_wsq_local_pop (&data);
1690 if (data && must_die) {
1691 InterlockedCompareExchange (&tp->destroy_thread, 1, 0);
1692 pulse_on_new_job (tp);
1701 down = mono_runtime_is_shutting_down ();
1702 if (!down && nt <= tp->min_threads)
1704 if (down || InterlockedCompareExchange (&tp->nthreads, nt - 1, nt) == nt) {
1705 #ifndef DISABLE_PERFCOUNTERS
1706 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, -1);
1712 fire_profiler_thread_end ();
1715 tp_finish_func (tp_hooks_user_data);
1719 mono_mutex_lock (&threads_lock);
1721 g_ptr_array_remove_fast (threads, mono_thread_current ()->internal_thread);
1722 mono_mutex_unlock (&threads_lock);
1732 g_assert_not_reached ();
1736 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
1738 *workerThreads = async_tp.max_threads - async_tp.busy_threads;
1739 *completionPortThreads = async_io_tp.max_threads - async_io_tp.busy_threads;
1743 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
1745 *workerThreads = async_tp.max_threads;
1746 *completionPortThreads = async_io_tp.max_threads;
1750 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
1752 *workerThreads = async_tp.min_threads;
1753 *completionPortThreads = async_io_tp.min_threads;
1757 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
1760 gint max_io_threads;
1762 max_threads = async_tp.max_threads;
1763 if (workerThreads <= 0 || workerThreads > max_threads)
1766 max_io_threads = async_io_tp.max_threads;
1767 if (completionPortThreads <= 0 || completionPortThreads > max_io_threads)
1770 InterlockedExchange (&async_tp.min_threads, workerThreads);
1771 InterlockedExchange (&async_io_tp.min_threads, completionPortThreads);
1772 if (workerThreads > async_tp.nthreads)
1773 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_tp, TRUE, SMALL_STACK);
1774 if (completionPortThreads > async_io_tp.nthreads)
1775 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_io_tp, TRUE, SMALL_STACK);
1780 ves_icall_System_Threading_ThreadPool_SetMaxThreads (gint workerThreads, gint completionPortThreads)
1783 gint min_io_threads;
1786 cpu_count = mono_cpu_count ();
1787 min_threads = async_tp.min_threads;
1788 if (workerThreads < min_threads || workerThreads < cpu_count)
1791 /* We don't really have the concept of completion ports. Do we care here? */
1792 min_io_threads = async_io_tp.min_threads;
1793 if (completionPortThreads < min_io_threads || completionPortThreads < cpu_count)
1796 InterlockedExchange (&async_tp.max_threads, workerThreads);
1797 InterlockedExchange (&async_io_tp.max_threads, completionPortThreads);
1802 * mono_install_threadpool_thread_hooks
1803 * @start_func: the function to be called right after a new threadpool thread is created. Can be NULL.
1804 * @finish_func: the function to be called right before a thredpool thread is exiting. Can be NULL.
1805 * @user_data: argument passed to @start_func and @finish_func.
1807 * @start_fun will be called right after a threadpool thread is created and @finish_func right before a threadpool thread exits.
1808 * The calls will be made from the thread itself.
1811 mono_install_threadpool_thread_hooks (MonoThreadPoolFunc start_func, MonoThreadPoolFunc finish_func, gpointer user_data)
1813 tp_start_func = start_func;
1814 tp_finish_func = finish_func;
1815 tp_hooks_user_data = user_data;
1819 * mono_install_threadpool_item_hooks
1820 * @begin_func: the function to be called before a threadpool work item processing starts.
1821 * @end_func: the function to be called after a threadpool work item is finished.
1822 * @user_data: argument passed to @begin_func and @end_func.
1824 * The calls will be made from the thread itself and from the same AppDomain
1825 * where the work item was executed.
1829 mono_install_threadpool_item_hooks (MonoThreadPoolItemFunc begin_func, MonoThreadPoolItemFunc end_func, gpointer user_data)
1831 tp_item_begin_func = begin_func;
1832 tp_item_end_func = end_func;
1833 tp_item_user_data = user_data;
1837 mono_internal_thread_unhandled_exception (MonoObject* exc)
1839 if (mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_CURRENT) {
1843 klass = exc->vtable->klass;
1844 unloaded = is_appdomainunloaded_exception (exc->vtable->domain, klass);
1845 if (!unloaded && klass != mono_defaults.threadabortexception_class) {
1846 mono_unhandled_exception (exc);
1847 if (mono_environment_exitcode_get () == 1)
1850 if (klass == mono_defaults.threadabortexception_class)
1851 mono_thread_internal_reset_abort (mono_thread_internal_current ());
1856 * Suspend creation of new threads.
1859 mono_thread_pool_suspend (void)
1861 if (use_ms_threadpool ()) {
1862 mono_threadpool_ms_suspend ();
1869 * Resume creation of new threads.
1872 mono_thread_pool_resume (void)
1874 if (use_ms_threadpool ()) {
1875 mono_threadpool_ms_resume ();