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);
836 ts = mono_msec_ticks ();
837 if (SleepEx (ms, TRUE) == 0)
839 ms -= (mono_msec_ticks () - ts);
840 if (mono_runtime_is_shutting_down ())
842 check_for_interruption_critical ();
843 } while (ms > 0 && i--);
844 mono_gc_set_skip_thread (FALSE);
846 if (mono_runtime_is_shutting_down ())
852 /* threadpool is cleaning up */
853 if (async_tp.pool_status == 2 || async_io_tp.pool_status == 2)
856 switch (monitor_state) {
857 case MONITOR_STATE_AWAKE:
858 num_waiting_iterations = 0;
860 case MONITOR_STATE_FALLING_ASLEEP:
861 if (++num_waiting_iterations == NUM_WAITING_ITERATIONS) {
862 if (monitor_state == MONITOR_STATE_FALLING_ASLEEP && InterlockedCompareExchange (&monitor_state, MONITOR_STATE_SLEEPING, MONITOR_STATE_FALLING_ASLEEP) == MONITOR_STATE_FALLING_ASLEEP) {
863 MONO_SEM_WAIT (&monitor_sem);
865 num_waiting_iterations = 0;
871 case MONITOR_STATE_SLEEPING:
872 g_assert_not_reached ();
875 for (i = 0; i < 2; i++) {
880 if (!tp->waiting && mono_cq_count (tp->queue) > 0)
881 threadpool_start_thread (tp);
883 gint8 nthreads_diff = monitor_heuristic (¤t, &history_size, history, tp);
885 if (nthreads_diff == 1)
886 threadpool_start_thread (tp);
887 else if (nthreads_diff == -1)
888 threadpool_kill_thread (tp);
895 mono_thread_pool_init_tls (void)
897 if (use_ms_threadpool ()) {
898 mono_threadpool_ms_init_tls ();
906 mono_thread_pool_init (void)
908 gint threads_per_cpu = 1;
913 if (use_ms_threadpool ()) {
914 mono_threadpool_ms_init ();
918 cpu_count = mono_cpu_count ();
923 result = InterlockedCompareExchange (&tp_inited, 1, 0);
932 MONO_GC_REGISTER_ROOT_FIXED (socket_io_data.sock_to_state);
933 mono_mutex_init_recursive (&socket_io_data.io_lock);
934 if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
935 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
936 if (threads_per_cpu < 1)
940 thread_count = MIN (cpu_count * threads_per_cpu, 100 * cpu_count);
941 threadpool_init (&async_tp, thread_count, MAX (100 * cpu_count, thread_count), async_invoke_thread);
942 threadpool_init (&async_io_tp, cpu_count * 2, cpu_count * 4, async_invoke_thread);
943 async_io_tp.is_io = TRUE;
945 async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
946 g_assert (async_call_klass);
948 mono_mutex_init (&threads_lock);
949 threads = g_ptr_array_sized_new (thread_count);
952 mono_mutex_init_recursive (&wsqs_lock);
953 wsqs = g_ptr_array_sized_new (MAX (100 * cpu_count, thread_count));
955 #ifndef DISABLE_PERFCOUNTERS
956 async_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "Work Items Added");
957 g_assert (async_tp.pc_nitems);
959 async_io_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "IO Work Items Added");
960 g_assert (async_io_tp.pc_nitems);
962 async_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of Threads");
963 g_assert (async_tp.pc_nthreads);
965 async_io_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of IO Threads");
966 g_assert (async_io_tp.pc_nthreads);
970 signal (SIGALRM, signal_handler);
974 MONO_SEM_INIT (&monitor_sem, 0);
975 monitor_state = MONITOR_STATE_AWAKE;
979 static MonoAsyncResult *
980 create_simple_asyncresult (MonoObject *target, MonoObject *state)
982 MonoDomain *domain = mono_domain_get ();
983 MonoAsyncResult *ares;
985 /* Don't call mono_async_result_new() to avoid capturing the context */
986 ares = (MonoAsyncResult *) mono_object_new (domain, mono_defaults.asyncresult_class);
987 MONO_OBJECT_SETREF (ares, async_delegate, target);
988 MONO_OBJECT_SETREF (ares, async_state, state);
993 icall_append_io_job (MonoObject *target, MonoSocketAsyncResult *state)
995 MonoAsyncResult *ares;
997 ares = create_simple_asyncresult (target, (MonoObject *) state);
999 if (use_ms_threadpool ()) {
1000 #ifndef DISABLE_SOCKETS
1001 mono_threadpool_ms_io_add (ares, state);
1006 socket_io_add (ares, state);
1010 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
1014 MonoAsyncResult *ares;
1017 if (use_ms_threadpool ())
1018 return mono_threadpool_ms_add (target, msg, async_callback, state);
1020 domain = mono_domain_get ();
1022 ac = (MonoAsyncCall*)mono_object_new (domain, async_call_klass);
1023 MONO_OBJECT_SETREF (ac, msg, msg);
1024 MONO_OBJECT_SETREF (ac, state, state);
1026 if (async_callback) {
1027 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
1028 MONO_OBJECT_SETREF (ac, cb_target, async_callback);
1031 ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
1032 MONO_OBJECT_SETREF (ares, async_delegate, target);
1034 #ifndef DISABLE_SOCKETS
1035 if (socket_io_filter (target, state)) {
1036 socket_io_add (ares, (MonoSocketAsyncResult *) state);
1040 threadpool_append_job (&async_tp, (MonoObject *) ares);
1045 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1050 if (use_ms_threadpool ()) {
1051 return mono_threadpool_ms_finish (ares, out_args, exc);
1057 /* check if already finished */
1058 mono_monitor_enter ((MonoObject *) ares);
1060 if (ares->endinvoke_called) {
1061 *exc = (MonoObject *) mono_get_exception_invalid_operation (NULL);
1062 mono_monitor_exit ((MonoObject *) ares);
1066 ares->endinvoke_called = 1;
1067 /* wait until we are really finished */
1068 if (!ares->completed) {
1069 if (ares->handle == NULL) {
1070 wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1071 g_assert(wait_event != 0);
1072 MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), wait_event));
1074 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
1076 mono_monitor_exit ((MonoObject *) ares);
1077 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
1079 mono_monitor_exit ((MonoObject *) ares);
1082 ac = (MonoAsyncCall *) ares->object_data;
1083 g_assert (ac != NULL);
1084 *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1085 *out_args = ac->out_args;
1091 threadpool_kill_idle_threads (ThreadPool *tp)
1095 n = (gint) InterlockedCompareExchange (&tp->max_threads, 0, -1);
1098 MONO_SEM_POST (&tp->new_job);
1103 mono_thread_pool_cleanup (void)
1105 if (use_ms_threadpool ()) {
1106 mono_threadpool_ms_cleanup ();
1110 if (InterlockedExchange (&async_io_tp.pool_status, 2) == 1) {
1111 socket_io_cleanup (&socket_io_data); /* Empty when DISABLE_SOCKETS is defined */
1112 threadpool_kill_idle_threads (&async_io_tp);
1115 if (async_io_tp.queue != NULL) {
1116 MONO_SEM_DESTROY (&async_io_tp.new_job);
1117 threadpool_free_queue (&async_io_tp);
1121 if (InterlockedExchange (&async_tp.pool_status, 2) == 1) {
1122 threadpool_kill_idle_threads (&async_tp);
1123 threadpool_free_queue (&async_tp);
1127 mono_mutex_lock (&threads_lock);
1129 g_ptr_array_free (threads, FALSE);
1131 mono_mutex_unlock (&threads_lock);
1135 mono_mutex_lock (&wsqs_lock);
1136 mono_wsq_cleanup ();
1138 g_ptr_array_free (wsqs, TRUE);
1140 mono_mutex_unlock (&wsqs_lock);
1141 MONO_SEM_DESTROY (&async_tp.new_job);
1144 MONO_SEM_DESTROY (&monitor_sem);
1148 threadpool_start_thread (ThreadPool *tp)
1152 MonoInternalThread *thread;
1154 stack_size = (!tp->is_io) ? 0 : SMALL_STACK;
1155 while (!mono_runtime_is_shutting_down () && (n = tp->nthreads) < tp->max_threads) {
1156 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n) {
1157 #ifndef DISABLE_PERFCOUNTERS
1158 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
1161 thread = mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE, stack_size);
1163 mono_mutex_lock (&threads_lock);
1164 thread = mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE, stack_size);
1165 g_assert (threads != NULL);
1166 g_ptr_array_add (threads, thread);
1167 mono_mutex_unlock (&threads_lock);
1177 pulse_on_new_job (ThreadPool *tp)
1180 MONO_SEM_POST (&tp->new_job);
1184 threadpool_kill_thread (ThreadPool *tp)
1186 if (tp->destroy_thread == 0 && InterlockedCompareExchange (&tp->destroy_thread, 1, 0) == 0)
1187 pulse_on_new_job (tp);
1191 icall_append_job (MonoObject *ar)
1193 threadpool_append_jobs (&async_tp, &ar, 1);
1197 threadpool_append_job (ThreadPool *tp, MonoObject *ar)
1199 threadpool_append_jobs (tp, &ar, 1);
1203 threadpool_append_async_io_jobs (MonoObject **jobs, gint njobs)
1205 threadpool_append_jobs (&async_io_tp, jobs, njobs);
1209 threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs)
1214 if (mono_runtime_is_shutting_down ())
1217 if (tp->pool_status == 0 && InterlockedCompareExchange (&tp->pool_status, 1, 0) == 0) {
1219 monitor_internal_thread = mono_thread_create_internal (mono_get_root_domain (), monitor_thread, NULL, TRUE, SMALL_STACK);
1220 monitor_internal_thread->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
1221 threadpool_start_thread (tp);
1223 /* Create on demand up to min_threads to avoid startup penalty for apps that don't use
1224 * the threadpool that much
1226 if (mono_config_is_server_mode ()) {
1227 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, tp, TRUE, SMALL_STACK);
1231 InterlockedAdd (&monitor_njobs, njobs);
1233 if (monitor_state == MONITOR_STATE_SLEEPING && InterlockedCompareExchange (&monitor_state, MONITOR_STATE_AWAKE, MONITOR_STATE_SLEEPING) == MONITOR_STATE_SLEEPING)
1234 MONO_SEM_POST (&monitor_sem);
1236 if (monitor_state == MONITOR_STATE_FALLING_ASLEEP)
1237 InterlockedCompareExchange (&monitor_state, MONITOR_STATE_AWAKE, MONITOR_STATE_FALLING_ASLEEP);
1239 for (i = 0; i < njobs; i++) {
1241 if (ar == NULL || mono_domain_is_unloading (ar->vtable->domain))
1242 continue; /* Might happen when cleaning domain jobs */
1243 threadpool_jobs_inc (ar);
1244 #ifndef DISABLE_PERFCOUNTERS
1245 mono_perfcounter_update_value (tp->pc_nitems, TRUE, 1);
1247 if (!tp->is_io && mono_wsq_local_push (ar))
1250 mono_cq_enqueue (tp->queue, ar);
1254 InterlockedAdd (&tp->njobs, njobs);
1257 for (i = 0; tp->waiting > 0 && i < MIN(njobs, tp->max_threads); i++)
1258 pulse_on_new_job (tp);
1262 threadpool_clear_queue (ThreadPool *tp, MonoDomain *domain)
1265 MonoMList *other = NULL;
1266 MonoCQ *queue = tp->queue;
1271 while (mono_cq_dequeue (queue, &obj)) {
1274 if (obj->vtable->domain != domain)
1275 other = mono_mlist_prepend (other, obj);
1276 threadpool_jobs_dec (obj);
1279 if (mono_runtime_is_shutting_down ())
1283 threadpool_append_job (tp, (MonoObject *) mono_mlist_get_data (other));
1284 other = mono_mlist_next (other);
1289 remove_sockstate_for_domain (gpointer key, gpointer value, gpointer user_data)
1291 MonoMList *list = value;
1292 gboolean remove = FALSE;
1294 MonoObject *data = mono_mlist_get_data (list);
1295 if (mono_object_domain (data) == user_data) {
1297 mono_mlist_set_data (list, NULL);
1299 list = mono_mlist_next (list);
1301 //FIXME is there some sort of additional unregistration we need to perform here?
1306 * Clean up the threadpool of all domain jobs.
1307 * Can only be called as part of the domain unloading process as
1308 * it will wait for all jobs to be visible to the interruption code.
1311 mono_thread_pool_remove_domain_jobs (MonoDomain *domain, int timeout)
1317 if (use_ms_threadpool ()) {
1318 return mono_threadpool_ms_remove_domain_jobs (domain, timeout);
1324 g_assert (domain->state == MONO_APPDOMAIN_UNLOADING);
1326 threadpool_clear_queue (&async_tp, domain);
1327 threadpool_clear_queue (&async_io_tp, domain);
1329 mono_mutex_lock (&socket_io_data.io_lock);
1330 if (socket_io_data.sock_to_state)
1331 mono_g_hash_table_foreach_remove (socket_io_data.sock_to_state, remove_sockstate_for_domain, domain);
1333 mono_mutex_unlock (&socket_io_data.io_lock);
1336 * There might be some threads out that could be about to execute stuff from the given domain.
1337 * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
1339 sem_handle = CreateSemaphore (NULL, 0, 1, NULL);
1341 domain->cleanup_semaphore = sem_handle;
1343 * The memory barrier here is required to have global ordering between assigning to cleanup_semaphone
1344 * and reading threadpool_jobs.
1345 * Otherwise this thread could read a stale version of threadpool_jobs and wait forever.
1347 mono_memory_write_barrier ();
1349 if (domain->threadpool_jobs && timeout != -1)
1350 start_time = mono_msec_ticks ();
1351 while (domain->threadpool_jobs) {
1352 WaitForSingleObject (sem_handle, timeout);
1353 if (timeout != -1 && (mono_msec_ticks () - start_time) > timeout) {
1359 domain->cleanup_semaphore = NULL;
1360 CloseHandle (sem_handle);
1365 threadpool_free_queue (ThreadPool *tp)
1367 mono_cq_destroy (tp->queue);
1372 mono_thread_pool_is_queue_array (MonoArray *o)
1374 if (use_ms_threadpool ()) {
1375 return mono_threadpool_ms_is_queue_array (o);
1378 // gpointer obj = o;
1380 // FIXME: need some fix in sgen code.
1390 mono_mutex_lock (&wsqs_lock);
1391 wsq = mono_wsq_create ();
1393 mono_mutex_unlock (&wsqs_lock);
1396 for (i = 0; i < wsqs->len; i++) {
1397 if (g_ptr_array_index (wsqs, i) == NULL) {
1398 wsqs->pdata [i] = wsq;
1399 mono_mutex_unlock (&wsqs_lock);
1403 g_ptr_array_add (wsqs, wsq);
1404 mono_mutex_unlock (&wsqs_lock);
1409 remove_wsq (MonoWSQ *wsq)
1416 mono_mutex_lock (&wsqs_lock);
1418 mono_mutex_unlock (&wsqs_lock);
1421 g_ptr_array_remove_fast (wsqs, wsq);
1424 * Only clean this up when shutting down, any other case will error out
1425 * if we're removing a queue that still has work items.
1427 if (mono_runtime_is_shutting_down ()) {
1428 while (mono_wsq_local_pop (&data)) {
1429 threadpool_jobs_dec (data);
1433 mono_wsq_destroy (wsq);
1434 mono_mutex_unlock (&wsqs_lock);
1438 try_steal (MonoWSQ *local_wsq, gpointer *data, gboolean retry)
1443 if (wsqs == NULL || data == NULL || *data != NULL)
1448 if (mono_runtime_is_shutting_down ())
1451 mono_mutex_lock (&wsqs_lock);
1452 for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
1455 wsq = wsqs->pdata [i];
1456 if (wsq == local_wsq || mono_wsq_count (wsq) == 0)
1458 mono_wsq_try_steal (wsqs->pdata [i], data, ms);
1459 if (*data != NULL) {
1460 mono_mutex_unlock (&wsqs_lock);
1464 mono_mutex_unlock (&wsqs_lock);
1466 } while (retry && ms < 11);
1470 dequeue_or_steal (ThreadPool *tp, gpointer *data, MonoWSQ *local_wsq)
1472 MonoCQ *queue = tp->queue;
1473 if (mono_runtime_is_shutting_down () || !queue)
1475 mono_cq_dequeue (queue, (MonoObject **) data);
1476 if (!tp->is_io && !*data)
1477 try_steal (local_wsq, data, FALSE);
1478 return (*data != NULL);
1482 should_i_die (ThreadPool *tp)
1484 gboolean result = FALSE;
1485 if (tp->destroy_thread == 1 && InterlockedCompareExchange (&tp->destroy_thread, 0, 1) == 1)
1486 result = (tp->nthreads > tp->min_threads);
1491 set_tp_thread_info (ThreadPool *tp)
1494 MonoInternalThread *thread = mono_thread_internal_current ();
1496 mono_profiler_thread_start (thread->tid);
1497 name = (tp->is_io) ? "IO Threadpool worker" : "Threadpool worker";
1498 mono_thread_set_name_internal (thread, mono_string_new (mono_domain_get (), name), FALSE);
1502 clear_thread_state (void)
1504 MonoInternalThread *thread = mono_thread_internal_current ();
1505 /* If the callee changes the background status, set it back to TRUE */
1506 mono_thread_clr_state (thread , ~ThreadState_Background);
1507 if (!mono_thread_test_state (thread , ThreadState_Background))
1508 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
1512 check_for_interruption_critical (void)
1514 MonoInternalThread *thread;
1515 /*RULE NUMBER ONE OF SKIP_THREAD: NEVER POKE MANAGED STATE.*/
1516 mono_gc_set_skip_thread (FALSE);
1518 thread = mono_thread_internal_current ();
1519 if (THREAD_WANTS_A_BREAK (thread))
1520 mono_thread_interruption_checkpoint ();
1522 /*RULE NUMBER TWO OF SKIP_THREAD: READ RULE NUMBER ONE.*/
1523 mono_gc_set_skip_thread (TRUE);
1527 fire_profiler_thread_end (void)
1529 MonoInternalThread *thread = mono_thread_internal_current ();
1530 mono_profiler_thread_end (thread->tid);
1534 async_invoke_thread (gpointer data)
1546 set_tp_thread_info (tp);
1549 tp_start_func (tp_hooks_user_data);
1553 MonoAsyncResult *ar;
1555 gboolean is_io_task;
1560 ar = (MonoAsyncResult *) data;
1562 InterlockedIncrement (&tp->busy_threads);
1563 domain = ((MonoObject *)ar)->vtable->domain;
1564 #ifndef DISABLE_SOCKETS
1565 klass = ((MonoObject *) data)->vtable->klass;
1566 is_io_task = !is_corlib_asyncresult (domain, klass);
1569 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1570 is_socket = is_socketasyncresult (domain, klass);
1572 switch (state->operation) {
1573 case AIO_OP_RECEIVE:
1574 state->total = ICALL_RECV (state);
1577 state->total = ICALL_SEND (state);
1582 /* worker threads invokes methods in different domains,
1583 * so we need to set the right domain here */
1586 if (mono_domain_is_unloading (domain) || mono_runtime_is_shutting_down ()) {
1587 threadpool_jobs_dec ((MonoObject *)ar);
1590 InterlockedDecrement (&tp->busy_threads);
1592 mono_thread_push_appdomain_ref (domain);
1593 if (threadpool_jobs_dec ((MonoObject *)ar)) {
1596 mono_thread_pop_appdomain_ref ();
1597 InterlockedDecrement (&tp->busy_threads);
1601 if (mono_domain_set (domain, FALSE)) {
1604 if (tp_item_begin_func)
1605 tp_item_begin_func (tp_item_user_data);
1607 exc = mono_async_invoke (tp, ar);
1608 if (tp_item_end_func)
1609 tp_item_end_func (tp_item_user_data);
1611 mono_internal_thread_unhandled_exception (exc);
1612 if (is_socket && tp->is_io) {
1613 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1615 if (state->completed && state->callback) {
1616 MonoAsyncResult *cb_ares;
1617 cb_ares = create_simple_asyncresult ((MonoObject *) state->callback,
1618 (MonoObject *) state);
1619 icall_append_job ((MonoObject *) cb_ares);
1622 mono_domain_set (mono_get_root_domain (), TRUE);
1624 mono_thread_pop_appdomain_ref ();
1625 InterlockedDecrement (&tp->busy_threads);
1626 clear_thread_state ();
1632 must_die = should_i_die (tp);
1634 mono_wsq_suspend (wsq);
1636 if (tp->is_io || !mono_wsq_local_pop (&data))
1637 dequeue_or_steal (tp, &data, wsq);
1641 while (!must_die && !data && n_naps < 4) {
1644 InterlockedIncrement (&tp->waiting);
1646 // Another thread may have added a job into its wsq since the last call to dequeue_or_steal
1647 // Check all the queues again before entering the wait loop
1648 dequeue_or_steal (tp, &data, wsq);
1650 InterlockedDecrement (&tp->waiting);
1654 mono_gc_set_skip_thread (TRUE);
1656 #if defined(__OpenBSD__)
1657 while (mono_cq_count (tp->queue) == 0 && (res = mono_sem_wait (&tp->new_job, TRUE)) == -1) {// && errno == EINTR) {
1659 while (mono_cq_count (tp->queue) == 0 && (res = mono_sem_timedwait (&tp->new_job, 2000, TRUE)) == -1) {// && errno == EINTR) {
1661 if (mono_runtime_is_shutting_down ())
1663 check_for_interruption_critical ();
1665 InterlockedDecrement (&tp->waiting);
1667 mono_gc_set_skip_thread (FALSE);
1669 if (mono_runtime_is_shutting_down ())
1671 must_die = should_i_die (tp);
1672 dequeue_or_steal (tp, &data, wsq);
1676 if (!data && !tp->is_io && !mono_runtime_is_shutting_down ()) {
1677 mono_wsq_local_pop (&data);
1678 if (data && must_die) {
1679 InterlockedCompareExchange (&tp->destroy_thread, 1, 0);
1680 pulse_on_new_job (tp);
1689 down = mono_runtime_is_shutting_down ();
1690 if (!down && nt <= tp->min_threads)
1692 if (down || InterlockedCompareExchange (&tp->nthreads, nt - 1, nt) == nt) {
1693 #ifndef DISABLE_PERFCOUNTERS
1694 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, -1);
1700 fire_profiler_thread_end ();
1703 tp_finish_func (tp_hooks_user_data);
1707 mono_mutex_lock (&threads_lock);
1709 g_ptr_array_remove_fast (threads, mono_thread_current ()->internal_thread);
1710 mono_mutex_unlock (&threads_lock);
1720 g_assert_not_reached ();
1724 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
1726 *workerThreads = async_tp.max_threads - async_tp.busy_threads;
1727 *completionPortThreads = async_io_tp.max_threads - async_io_tp.busy_threads;
1731 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
1733 *workerThreads = async_tp.max_threads;
1734 *completionPortThreads = async_io_tp.max_threads;
1738 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
1740 *workerThreads = async_tp.min_threads;
1741 *completionPortThreads = async_io_tp.min_threads;
1745 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
1748 gint max_io_threads;
1750 max_threads = async_tp.max_threads;
1751 if (workerThreads <= 0 || workerThreads > max_threads)
1754 max_io_threads = async_io_tp.max_threads;
1755 if (completionPortThreads <= 0 || completionPortThreads > max_io_threads)
1758 InterlockedExchange (&async_tp.min_threads, workerThreads);
1759 InterlockedExchange (&async_io_tp.min_threads, completionPortThreads);
1760 if (workerThreads > async_tp.nthreads)
1761 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_tp, TRUE, SMALL_STACK);
1762 if (completionPortThreads > async_io_tp.nthreads)
1763 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_io_tp, TRUE, SMALL_STACK);
1768 ves_icall_System_Threading_ThreadPool_SetMaxThreads (gint workerThreads, gint completionPortThreads)
1771 gint min_io_threads;
1774 cpu_count = mono_cpu_count ();
1775 min_threads = async_tp.min_threads;
1776 if (workerThreads < min_threads || workerThreads < cpu_count)
1779 /* We don't really have the concept of completion ports. Do we care here? */
1780 min_io_threads = async_io_tp.min_threads;
1781 if (completionPortThreads < min_io_threads || completionPortThreads < cpu_count)
1784 InterlockedExchange (&async_tp.max_threads, workerThreads);
1785 InterlockedExchange (&async_io_tp.max_threads, completionPortThreads);
1790 * mono_install_threadpool_thread_hooks
1791 * @start_func: the function to be called right after a new threadpool thread is created. Can be NULL.
1792 * @finish_func: the function to be called right before a thredpool thread is exiting. Can be NULL.
1793 * @user_data: argument passed to @start_func and @finish_func.
1795 * @start_fun will be called right after a threadpool thread is created and @finish_func right before a threadpool thread exits.
1796 * The calls will be made from the thread itself.
1799 mono_install_threadpool_thread_hooks (MonoThreadPoolFunc start_func, MonoThreadPoolFunc finish_func, gpointer user_data)
1801 tp_start_func = start_func;
1802 tp_finish_func = finish_func;
1803 tp_hooks_user_data = user_data;
1807 * mono_install_threadpool_item_hooks
1808 * @begin_func: the function to be called before a threadpool work item processing starts.
1809 * @end_func: the function to be called after a threadpool work item is finished.
1810 * @user_data: argument passed to @begin_func and @end_func.
1812 * The calls will be made from the thread itself and from the same AppDomain
1813 * where the work item was executed.
1817 mono_install_threadpool_item_hooks (MonoThreadPoolItemFunc begin_func, MonoThreadPoolItemFunc end_func, gpointer user_data)
1819 tp_item_begin_func = begin_func;
1820 tp_item_end_func = end_func;
1821 tp_item_user_data = user_data;
1825 mono_internal_thread_unhandled_exception (MonoObject* exc)
1827 if (mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_CURRENT) {
1831 klass = exc->vtable->klass;
1832 unloaded = is_appdomainunloaded_exception (exc->vtable->domain, klass);
1833 if (!unloaded && klass != mono_defaults.threadabortexception_class) {
1834 mono_unhandled_exception (exc);
1835 if (mono_environment_exitcode_get () == 1)
1838 if (klass == mono_defaults.threadabortexception_class)
1839 mono_thread_internal_reset_abort (mono_thread_internal_current ());
1844 * Suspend creation of new threads.
1847 mono_thread_pool_suspend (void)
1849 if (use_ms_threadpool ()) {
1850 mono_threadpool_ms_suspend ();
1857 * Resume creation of new threads.
1860 mono_thread_pool_resume (void)
1862 if (use_ms_threadpool ()) {
1863 mono_threadpool_ms_resume ();