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/io-layer/io-layer.h>
30 #include <mono/utils/mono-time.h>
31 #include <mono/utils/mono-proclib.h>
32 #include <mono/utils/mono-semaphore.h>
33 #include <mono/utils/atomic.h>
35 #ifdef HAVE_SYS_TIME_H
38 #include <sys/types.h>
45 #ifdef HAVE_SYS_SOCKET_H
46 #include <sys/socket.h>
48 #include <mono/utils/mono-poll.h>
50 #include <sys/epoll.h>
53 #include <sys/event.h>
57 #ifndef DISABLE_SOCKETS
58 #include "mono/io-layer/socket-wrappers.h"
61 #include "threadpool.h"
63 #define THREAD_WANTS_A_BREAK(t) ((t->state & (ThreadState_StopRequested | \
64 ThreadState_SuspendRequested)) != 0)
66 #define SMALL_STACK (128 * (sizeof (gpointer) / 4) * 1024)
68 /* DEBUG: prints tp data every 2s */
71 /* mono_thread_pool_init called */
72 static volatile int tp_inited;
82 MONITOR_STATE_FALLING_ASLEEP,
83 MONITOR_STATE_SLEEPING
87 mono_mutex_t io_lock; /* access to sock_to_state */
88 int inited; // 0 -> not initialized , 1->initializing, 2->initialized, 3->cleaned up
89 MonoGHashTable *sock_to_state;
93 void (*modify) (gpointer p, int fd, int operation, int events, gboolean is_new);
94 void (*wait) (gpointer sock_data);
95 void (*shutdown) (gpointer event_data);
98 static SocketIOData socket_io_data;
100 /* Keep in sync with the System.MonoAsyncCall class which provides GC tracking */
103 MonoMethodMessage *msg;
104 MonoMethod *cb_method;
105 MonoDelegate *cb_target;
113 MonoCQ *queue; /* GC root */
115 volatile gint waiting; /* threads waiting for a work item */
118 volatile gint pool_status; /* 0 -> not initialized, 1 -> initialized, 2 -> cleaning up */
119 /* min, max, n and busy -> Interlocked */
120 volatile gint min_threads;
121 volatile gint max_threads;
122 volatile gint nthreads;
123 volatile gint busy_threads;
125 void (*async_invoke) (gpointer data);
126 void *pc_nitems; /* Performance counter for total number of items in added */
127 void *pc_nthreads; /* Performance counter for total number of active threads */
129 volatile gint destroy_thread;
131 volatile gint32 njobs;
133 volatile gint32 nexecuted;
137 static ThreadPool async_tp;
138 static ThreadPool async_io_tp;
140 static void async_invoke_thread (gpointer data);
141 static MonoObject *mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares);
142 static void threadpool_free_queue (ThreadPool *tp);
143 static void threadpool_append_job (ThreadPool *tp, MonoObject *ar);
144 static void threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs);
145 static void threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer));
146 static void threadpool_start_idle_threads (ThreadPool *tp);
147 static void threadpool_kill_idle_threads (ThreadPool *tp);
148 static gboolean threadpool_start_thread (ThreadPool *tp);
149 static void threadpool_kill_thread (ThreadPool *tp);
150 static void monitor_thread (gpointer data);
151 static void socket_io_cleanup (SocketIOData *data);
152 static MonoObject *get_io_event (MonoMList **list, gint event);
153 static int get_events_from_list (MonoMList *list);
154 static int get_event_from_state (MonoSocketAsyncResult *state);
155 static void check_for_interruption_critical (void);
157 static MonoClass *async_call_klass;
158 static MonoClass *socket_async_call_klass;
159 static MonoClass *process_async_call_klass;
161 static GPtrArray *wsqs;
162 mono_mutex_t wsqs_lock;
163 static gboolean suspended;
165 static volatile gint32 monitor_njobs = 0;
166 static volatile gint32 monitor_state;
167 static MonoSemType monitor_sem;
168 static MonoInternalThread *monitor_internal_thread;
171 static MonoThreadPoolFunc tp_start_func;
172 static MonoThreadPoolFunc tp_finish_func;
173 static gpointer tp_hooks_user_data;
174 static MonoThreadPoolItemFunc tp_item_begin_func;
175 static MonoThreadPoolItemFunc tp_item_end_func;
176 static gpointer tp_item_user_data;
186 AIO_OP_RECV_JUST_CALLBACK,
187 AIO_OP_SEND_JUST_CALLBACK,
191 AIO_OP_ACCEPTRECEIVE,
192 AIO_OP_RECEIVE_BUFFERS,
197 #include <mono/metadata/tpool-poll.c>
199 #include <mono/metadata/tpool-epoll.c>
200 #elif defined(USE_KQUEUE_FOR_THREADPOOL)
201 #include <mono/metadata/tpool-kqueue.c>
204 * Functions to check whenever a class is given system class. We need to cache things in MonoDomain since some of the
205 * assemblies can be unloaded.
209 is_system_type (MonoDomain *domain, MonoClass *klass)
211 if (domain->system_image == NULL)
212 domain->system_image = mono_image_loaded ("System");
214 return klass->image == domain->system_image;
218 is_corlib_type (MonoDomain *domain, MonoClass *klass)
220 return klass->image == mono_defaults.corlib;
224 * Note that we call it is_socket_type() where 'socket' refers to the image
225 * that contains the System.Net.Sockets.Socket type.
228 is_socket_type (MonoDomain *domain, MonoClass *klass)
230 return is_system_type (domain, klass);
233 #define check_type_cached(domain, ASSEMBLY, _class, _namespace, _name, loc) do { \
235 return *loc == _class; \
236 if (is_##ASSEMBLY##_type (domain, _class) && !strcmp (_name, _class->name) && !strcmp (_namespace, _class->name_space)) { \
243 #define check_corlib_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, corlib, _class, _namespace, _name, loc)
245 #define check_socket_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, socket, _class, _namespace, _name, loc)
247 #define check_system_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, system, _class, _namespace, _name, loc)
250 is_corlib_asyncresult (MonoDomain *domain, MonoClass *klass)
252 check_corlib_type_cached (domain, klass, "System.Runtime.Remoting.Messaging", "AsyncResult", &domain->corlib_asyncresult_class);
256 is_socket (MonoDomain *domain, MonoClass *klass)
258 check_socket_type_cached (domain, klass, "System.Net.Sockets", "Socket", &domain->socket_class);
262 is_socketasyncresult (MonoDomain *domain, MonoClass *klass)
264 return (klass->nested_in &&
265 is_socket (domain, klass->nested_in) &&
266 !strcmp (klass->name, "SocketAsyncResult"));
270 is_socketasynccall (MonoDomain *domain, MonoClass *klass)
272 return (klass->nested_in &&
273 is_socket (domain, klass->nested_in) &&
274 !strcmp (klass->name, "SocketAsyncCall"));
278 is_appdomainunloaded_exception (MonoDomain *domain, MonoClass *klass)
280 check_corlib_type_cached (domain, klass, "System", "AppDomainUnloadedException", &domain->ad_unloaded_ex_class);
284 is_sd_process (MonoDomain *domain, MonoClass *klass)
286 check_system_type_cached (domain, klass, "System.Diagnostics", "Process", &domain->process_class);
290 is_sdp_asyncreadhandler (MonoDomain *domain, MonoClass *klass)
293 return (klass->nested_in &&
294 is_sd_process (domain, klass->nested_in) &&
295 !strcmp (klass->name, "AsyncReadHandler"));
299 #ifdef DISABLE_SOCKETS
301 #define socket_io_cleanup(x)
304 get_event_from_state (MonoSocketAsyncResult *state)
306 g_assert_not_reached ();
311 get_events_from_list (MonoMList *list)
319 socket_io_cleanup (SocketIOData *data)
321 mono_mutex_lock (&data->io_lock);
322 if (data->inited != 2) {
323 mono_mutex_unlock (&data->io_lock);
327 data->shutdown (data->event_data);
328 mono_mutex_unlock (&data->io_lock);
332 get_event_from_state (MonoSocketAsyncResult *state)
334 switch (state->operation) {
337 case AIO_OP_RECV_JUST_CALLBACK:
338 case AIO_OP_RECEIVEFROM:
339 case AIO_OP_READPIPE:
340 case AIO_OP_ACCEPTRECEIVE:
341 case AIO_OP_RECEIVE_BUFFERS:
344 case AIO_OP_SEND_JUST_CALLBACK:
347 case AIO_OP_SEND_BUFFERS:
348 case AIO_OP_DISCONNECT:
350 default: /* Should never happen */
351 g_message ("get_event_from_state: unknown value in switch!!!");
357 get_events_from_list (MonoMList *list)
359 MonoSocketAsyncResult *state;
362 while (list && (state = (MonoSocketAsyncResult *)mono_mlist_get_data (list))) {
363 events |= get_event_from_state (state);
364 list = mono_mlist_next (list);
370 #define ICALL_RECV(x) ves_icall_System_Net_Sockets_Socket_Receive_internal (\
371 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
372 x->socket_flags, &x->error);
374 #define ICALL_SEND(x) ves_icall_System_Net_Sockets_Socket_Send_internal (\
375 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
376 x->socket_flags, &x->error);
378 #endif /* !DISABLE_SOCKETS */
381 threadpool_jobs_inc (MonoObject *obj)
384 InterlockedIncrement (&obj->vtable->domain->threadpool_jobs);
388 threadpool_jobs_dec (MonoObject *obj)
396 domain = obj->vtable->domain;
397 remaining_jobs = InterlockedDecrement (&domain->threadpool_jobs);
398 if (remaining_jobs == 0 && domain->cleanup_semaphore) {
399 ReleaseSemaphore (domain->cleanup_semaphore, 1, NULL);
406 get_io_event (MonoMList **list, gint event)
416 state = mono_mlist_get_data (current);
417 if (get_event_from_state ((MonoSocketAsyncResult *) state) == event)
422 current = mono_mlist_next (current);
427 mono_mlist_set_next (prev, mono_mlist_next (current));
429 *list = mono_mlist_next (*list);
437 * select/poll wake up when a socket is closed, but epoll just removes
438 * the socket from its internal list without notification.
441 mono_thread_pool_remove_socket (int sock)
444 MonoSocketAsyncResult *state;
447 if (socket_io_data.inited == 0)
450 mono_mutex_lock (&socket_io_data.io_lock);
451 if (socket_io_data.sock_to_state == NULL) {
452 mono_mutex_unlock (&socket_io_data.io_lock);
455 list = mono_g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
457 mono_g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
458 mono_mutex_unlock (&socket_io_data.io_lock);
461 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
462 if (state->operation == AIO_OP_RECEIVE)
463 state->operation = AIO_OP_RECV_JUST_CALLBACK;
464 else if (state->operation == AIO_OP_SEND)
465 state->operation = AIO_OP_SEND_JUST_CALLBACK;
467 ares = get_io_event (&list, MONO_POLLIN);
468 threadpool_append_job (&async_io_tp, ares);
470 ares = get_io_event (&list, MONO_POLLOUT);
471 threadpool_append_job (&async_io_tp, ares);
477 init_event_system (SocketIOData *data)
480 if (data->event_system == EPOLL_BACKEND) {
481 data->event_data = tp_epoll_init (data);
482 if (data->event_data == NULL) {
483 if (g_getenv ("MONO_DEBUG"))
484 g_message ("Falling back to poll()");
485 data->event_system = POLL_BACKEND;
488 #elif defined(USE_KQUEUE_FOR_THREADPOOL)
489 if (data->event_system == KQUEUE_BACKEND)
490 data->event_data = tp_kqueue_init (data);
492 if (data->event_system == POLL_BACKEND)
493 data->event_data = tp_poll_init (data);
497 socket_io_init (SocketIOData *data)
501 if (data->inited >= 2) // 2 -> initialized, 3-> cleaned up
504 inited = InterlockedCompareExchange (&data->inited, 1, 0);
507 if (data->inited >= 2)
513 mono_mutex_lock (&data->io_lock);
514 data->sock_to_state = mono_g_hash_table_new_type (g_direct_hash, g_direct_equal, MONO_HASH_VALUE_GC);
516 data->event_system = EPOLL_BACKEND;
517 #elif defined(USE_KQUEUE_FOR_THREADPOOL)
518 data->event_system = KQUEUE_BACKEND;
520 data->event_system = POLL_BACKEND;
522 if (g_getenv ("MONO_DISABLE_AIO") != NULL)
523 data->event_system = POLL_BACKEND;
525 init_event_system (data);
526 mono_thread_create_internal (mono_get_root_domain (), data->wait, data, TRUE, SMALL_STACK);
527 mono_mutex_unlock (&data->io_lock);
529 threadpool_start_thread (&async_io_tp);
533 socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
536 SocketIOData *data = &socket_io_data;
541 socket_io_init (&socket_io_data);
542 if (mono_runtime_is_shutting_down () || data->inited == 3 || data->sock_to_state == NULL)
544 if (async_tp.pool_status == 2)
547 MONO_OBJECT_SETREF (state, ares, ares);
549 fd = GPOINTER_TO_INT (state->handle);
550 mono_mutex_lock (&data->io_lock);
551 if (data->sock_to_state == NULL) {
552 mono_mutex_unlock (&data->io_lock);
555 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
557 list = mono_mlist_alloc ((MonoObject*)state);
560 list = mono_mlist_append (list, (MonoObject*)state);
564 mono_g_hash_table_replace (data->sock_to_state, state->handle, list);
565 ievt = get_events_from_list (list);
566 /* The modify function leaves the io_lock critical section. */
567 data->modify (data, fd, state->operation, ievt, is_new);
570 #ifndef DISABLE_SOCKETS
572 socket_io_filter (MonoObject *target, MonoObject *state)
575 MonoSocketAsyncResult *sock_res;
579 if (target == NULL || state == NULL)
582 domain = target->vtable->domain;
583 klass = target->vtable->klass;
584 if (socket_async_call_klass == NULL && is_socketasynccall (domain, klass))
585 socket_async_call_klass = klass;
587 if (process_async_call_klass == NULL && is_sdp_asyncreadhandler (domain, klass))
588 process_async_call_klass = klass;
590 if (klass != socket_async_call_klass && klass != process_async_call_klass)
593 sock_res = (MonoSocketAsyncResult *) state;
594 op = sock_res->operation;
595 if (op < AIO_OP_FIRST || op >= AIO_OP_LAST)
600 #endif /* !DISABLE_SOCKETS */
602 /* Returns the exception thrown when invoking, if any */
604 mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares)
606 ASyncCall *ac = (ASyncCall *)ares->object_data;
607 MonoObject *res, *exc = NULL;
608 MonoArray *out_args = NULL;
609 HANDLE wait_event = NULL;
610 MonoInternalThread *thread = mono_thread_internal_current ();
612 if (ares->execution_context) {
613 /* use captured ExecutionContext (if available) */
614 MONO_OBJECT_SETREF (ares, original_context, mono_thread_get_execution_context ());
615 mono_thread_set_execution_context (ares->execution_context);
617 ares->original_context = NULL;
621 /* Fast path from ThreadPool.*QueueUserWorkItem */
622 void *pa = ares->async_state;
623 /* The debugger needs this */
624 thread->async_invoke_method = ((MonoDelegate*)ares->async_delegate)->method;
625 res = mono_runtime_delegate_invoke (ares->async_delegate, &pa, &exc);
626 thread->async_invoke_method = NULL;
628 MonoObject *cb_exc = NULL;
631 res = mono_message_invoke (ares->async_delegate, ac->msg, &exc, &out_args);
632 MONO_OBJECT_SETREF (ac, res, res);
633 MONO_OBJECT_SETREF (ac, msg->exc, exc);
634 MONO_OBJECT_SETREF (ac, out_args, out_args);
636 mono_monitor_enter ((MonoObject *) ares);
638 if (ares->handle != NULL)
639 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
640 mono_monitor_exit ((MonoObject *) ares);
641 /* notify listeners */
642 if (wait_event != NULL)
643 SetEvent (wait_event);
645 /* call async callback if cb_method != null*/
646 if (ac != NULL && ac->cb_method) {
649 thread->async_invoke_method = ac->cb_method;
650 mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &cb_exc);
651 thread->async_invoke_method = NULL;
658 /* restore original thread execution context if flow isn't suppressed, i.e. non null */
659 if (ares->original_context) {
660 mono_thread_set_execution_context (ares->original_context);
661 ares->original_context = NULL;
665 InterlockedDecrement (&tp->njobs);
668 InterlockedIncrement (&tp->nexecuted);
670 if (InterlockedDecrement (&monitor_njobs) == 0)
671 monitor_state = MONITOR_STATE_FALLING_ASLEEP;
677 threadpool_start_idle_threads (ThreadPool *tp)
682 stack_size = (!tp->is_io) ? 0 : SMALL_STACK;
686 if (n >= tp->min_threads)
688 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n)
691 #ifndef DISABLE_PERFCOUNTERS
692 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
694 mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE, stack_size);
700 threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer))
702 memset (tp, 0, sizeof (ThreadPool));
703 tp->min_threads = min_threads;
704 tp->max_threads = max_threads;
705 tp->async_invoke = async_invoke;
706 tp->queue = mono_cq_create ();
707 MONO_SEM_INIT (&tp->new_job, 0);
710 #ifndef DISABLE_PERFCOUNTERS
712 init_perf_counter (const char *category, const char *counter)
714 MonoString *category_str;
715 MonoString *counter_str;
721 if (category == NULL || counter == NULL)
723 root = mono_get_root_domain ();
724 category_str = mono_string_new (root, category);
725 counter_str = mono_string_new (root, counter);
726 machine = mono_string_new (root, ".");
727 return mono_perfcounter_get_impl (category_str, counter_str, NULL, machine, &type, &custom);
733 print_pool_info (ThreadPool *tp)
736 // if (tp->tail - tp->head == 0)
739 g_print ("Pool status? %d\n", InterlockedCompareExchange (&tp->pool_status, 0, 0));
740 g_print ("Min. threads: %d\n", InterlockedCompareExchange (&tp->min_threads, 0, 0));
741 g_print ("Max. threads: %d\n", InterlockedCompareExchange (&tp->max_threads, 0, 0));
742 g_print ("nthreads: %d\n", InterlockedCompareExchange (&tp->nthreads, 0, 0));
743 g_print ("busy threads: %d\n", InterlockedCompareExchange (&tp->busy_threads, 0, 0));
744 g_print ("Waiting: %d\n", InterlockedCompareExchange (&tp->waiting, 0, 0));
745 g_print ("Queued: %d\n", (tp->tail - tp->head));
746 if (tp == &async_tp) {
748 mono_mutex_lock (&wsqs_lock);
749 for (i = 0; i < wsqs->len; i++) {
750 g_print ("\tWSQ %d: %d\n", i, mono_wsq_count (g_ptr_array_index (wsqs, i)));
752 mono_mutex_unlock (&wsqs_lock);
754 g_print ("\tSockets: %d\n", mono_g_hash_table_size (socket_io_data.sock_to_state));
756 g_print ("-------------\n");
760 signal_handler (int signo)
765 g_print ("\n-----Non-IO-----\n");
766 print_pool_info (tp);
768 g_print ("\n-----IO-----\n");
769 print_pool_info (tp);
774 #define SAMPLES_PERIOD 500
775 #define HISTORY_SIZE 10
776 /* number of iteration without any jobs
777 in the queue before going to sleep */
778 #define NUM_WAITING_ITERATIONS 10
787 monitor_heuristic (gint16 *current, gint16 *history_size, SamplesHistory *history, ThreadPool *tp)
794 * The following heuristic tries to approach the optimal number of threads to maximize jobs throughput. To
795 * achieve this, it simply stores the number of jobs executed (nexecuted), the number of Threads (nthreads)
796 * and the decision (nthreads_diff) for the past HISTORY_SIZE periods of time, each period being of
797 * duration SAMPLES_PERIOD ms. This history gives us an insight into what happened, and to see if we should
798 * increase or reduce the number of threads by comparing the last period (current) to the best one.
800 * The algorithm can be describe as following :
801 * - if we have a better throughput than the best period : we should either increase the number of threads
802 * in case we already have more threads, either reduce the number of threads if we have less threads; this
803 * is equivalent to move away from the number of threads of the best period, because we are currently better
804 * - if we have a worse throughput than the best period : we should either decrease the number of threads if
805 * we have more threads, either increase the number of threads if we have less threads; this is equivalent
806 * to get closer to the number of threads of the best period, because we are currently worse
809 *history_size = MIN (*history_size + 1, HISTORY_SIZE);
810 cur = *current = (*current + 1) % *history_size;
812 history [cur].nthreads = tp->nthreads;
813 history [cur].nexecuted = InterlockedExchange (&tp->nexecuted, 0);
816 /* if we have waiting thread in the pool, then do not create a new one */
817 history [cur].nthreads_diff = tp->waiting > 1 ? -1 : 0;
819 } else if (tp->nthreads < tp->min_threads) {
820 history [cur].nthreads_diff = 1;
822 } else if (*history_size <= 1) {
823 /* first iteration, let's add a thread by default */
824 history [cur].nthreads_diff = 1;
827 max = cur == 0 ? 1 : 0;
828 for (i = 0; i < *history_size; i++) {
831 if (history [i].nexecuted > history [max].nexecuted)
835 if (history [cur].nexecuted >= history [max].nexecuted) {
836 /* we improved the situation, let's continue ! */
837 history [cur].nthreads_diff = history [cur].nthreads >= history [max].nthreads ? 1 : -1;
840 /* we made it worse, let's return to previous situation */
841 history [cur].nthreads_diff = history [cur].nthreads >= history [max].nthreads ? -1 : 1;
847 printf ("monitor_thread: decision: %1d, history [current]: {nexecuted: %5d, nthreads: %3d, waiting: %2d, nthreads_diff: %2d}, history [max]: {nexecuted: %5d, nthreads: %3d}\n",
848 decision, history [cur].nexecuted, history [cur].nthreads, tp->waiting, history [cur].nthreads_diff, history [max].nexecuted, history [max].nthreads);
851 return history [cur].nthreads_diff;
855 monitor_thread (gpointer unused)
857 ThreadPool *pools [2];
858 MonoInternalThread *thread;
862 gint8 num_waiting_iterations = 0;
864 gint16 history_size = 0, current = -1;
865 SamplesHistory *history = malloc (sizeof (SamplesHistory) * HISTORY_SIZE);
867 pools [0] = &async_tp;
868 pools [1] = &async_io_tp;
869 thread = mono_thread_internal_current ();
870 ves_icall_System_Threading_Thread_SetName_internal (thread, mono_string_new (mono_domain_get (), "Threadpool monitor"));
873 i = 10; //number of spurious awakes we tolerate before doing a round of rebalancing.
876 ts = mono_msec_ticks ();
877 if (SleepEx (ms, TRUE) == 0)
879 ms -= (mono_msec_ticks () - ts);
880 if (mono_runtime_is_shutting_down ())
882 if (THREAD_WANTS_A_BREAK (thread))
883 mono_thread_interruption_checkpoint ();
884 } while (ms > 0 && i--);
886 if (mono_runtime_is_shutting_down ())
892 switch (monitor_state) {
893 case MONITOR_STATE_AWAKE:
894 num_waiting_iterations = 0;
896 case MONITOR_STATE_FALLING_ASLEEP:
897 if (++num_waiting_iterations == NUM_WAITING_ITERATIONS) {
898 if (monitor_state == MONITOR_STATE_FALLING_ASLEEP && InterlockedCompareExchange (&monitor_state, MONITOR_STATE_SLEEPING, MONITOR_STATE_FALLING_ASLEEP) == MONITOR_STATE_FALLING_ASLEEP) {
899 MONO_SEM_WAIT (&monitor_sem);
901 num_waiting_iterations = 0;
907 case MONITOR_STATE_SLEEPING:
908 g_assert_not_reached ();
911 for (i = 0; i < 2; i++) {
916 if (!tp->waiting && mono_cq_count (tp->queue) > 0)
917 threadpool_start_thread (tp);
919 gint8 nthreads_diff = monitor_heuristic (¤t, &history_size, history, tp);
921 if (nthreads_diff > 0)
922 threadpool_start_thread (tp);
923 else if (nthreads_diff < 0)
924 threadpool_kill_thread (tp);
931 mono_thread_pool_init_tls (void)
937 mono_thread_pool_init (void)
939 gint threads_per_cpu = 1;
941 gint cpu_count = mono_cpu_count ();
947 result = InterlockedCompareExchange (&tp_inited, 1, 0);
956 MONO_GC_REGISTER_ROOT_FIXED (socket_io_data.sock_to_state);
957 mono_mutex_init_recursive (&socket_io_data.io_lock);
958 if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
959 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
960 if (threads_per_cpu < 1)
964 thread_count = MIN (cpu_count * threads_per_cpu, 100 * cpu_count);
965 threadpool_init (&async_tp, thread_count, MAX (100 * cpu_count, thread_count), async_invoke_thread);
966 threadpool_init (&async_io_tp, cpu_count * 2, cpu_count * 4, async_invoke_thread);
967 async_io_tp.is_io = TRUE;
969 async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
970 g_assert (async_call_klass);
972 mono_mutex_init_recursive (&wsqs_lock);
973 wsqs = g_ptr_array_sized_new (MAX (100 * cpu_count, thread_count));
975 #ifndef DISABLE_PERFCOUNTERS
976 async_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "Work Items Added");
977 g_assert (async_tp.pc_nitems);
979 async_io_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "IO Work Items Added");
980 g_assert (async_io_tp.pc_nitems);
982 async_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of Threads");
983 g_assert (async_tp.pc_nthreads);
985 async_io_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of IO Threads");
986 g_assert (async_io_tp.pc_nthreads);
990 signal (SIGALRM, signal_handler);
994 MONO_SEM_INIT (&monitor_sem, 0);
995 monitor_state = MONITOR_STATE_AWAKE;
999 static MonoAsyncResult *
1000 create_simple_asyncresult (MonoObject *target, MonoObject *state)
1002 MonoDomain *domain = mono_domain_get ();
1003 MonoAsyncResult *ares;
1005 /* Don't call mono_async_result_new() to avoid capturing the context */
1006 ares = (MonoAsyncResult *) mono_object_new (domain, mono_defaults.asyncresult_class);
1007 MONO_OBJECT_SETREF (ares, async_delegate, target);
1008 MONO_OBJECT_SETREF (ares, async_state, state);
1013 icall_append_io_job (MonoObject *target, MonoSocketAsyncResult *state)
1015 MonoAsyncResult *ares;
1017 ares = create_simple_asyncresult (target, (MonoObject *) state);
1018 socket_io_add (ares, state);
1022 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
1025 MonoDomain *domain = mono_domain_get ();
1026 MonoAsyncResult *ares;
1029 ac = (ASyncCall*)mono_object_new (domain, async_call_klass);
1030 MONO_OBJECT_SETREF (ac, msg, msg);
1031 MONO_OBJECT_SETREF (ac, state, state);
1033 if (async_callback) {
1034 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
1035 MONO_OBJECT_SETREF (ac, cb_target, async_callback);
1038 ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
1039 MONO_OBJECT_SETREF (ares, async_delegate, target);
1041 #ifndef DISABLE_SOCKETS
1042 if (socket_io_filter (target, state)) {
1043 socket_io_add (ares, (MonoSocketAsyncResult *) state);
1047 threadpool_append_job (&async_tp, (MonoObject *) ares);
1052 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1060 /* check if already finished */
1061 mono_monitor_enter ((MonoObject *) ares);
1063 if (ares->endinvoke_called) {
1064 *exc = (MonoObject *) mono_get_exception_invalid_operation (NULL);
1065 mono_monitor_exit ((MonoObject *) ares);
1069 ares->endinvoke_called = 1;
1070 /* wait until we are really finished */
1071 if (!ares->completed) {
1072 if (ares->handle == NULL) {
1073 wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1074 g_assert(wait_event != 0);
1075 MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), wait_event));
1077 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
1079 mono_monitor_exit ((MonoObject *) ares);
1080 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
1082 mono_monitor_exit ((MonoObject *) ares);
1085 ac = (ASyncCall *) ares->object_data;
1086 g_assert (ac != NULL);
1087 *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1088 *out_args = ac->out_args;
1094 threadpool_kill_idle_threads (ThreadPool *tp)
1098 n = (gint) InterlockedCompareExchange (&tp->max_threads, 0, -1);
1101 MONO_SEM_POST (&tp->new_job);
1106 mono_thread_pool_cleanup (void)
1108 if (InterlockedExchange (&async_io_tp.pool_status, 2) == 1) {
1109 socket_io_cleanup (&socket_io_data); /* Empty when DISABLE_SOCKETS is defined */
1110 threadpool_kill_idle_threads (&async_io_tp);
1113 if (async_io_tp.queue != NULL) {
1114 MONO_SEM_DESTROY (&async_io_tp.new_job);
1115 threadpool_free_queue (&async_io_tp);
1119 if (InterlockedExchange (&async_tp.pool_status, 2) == 1) {
1120 threadpool_kill_idle_threads (&async_tp);
1121 threadpool_free_queue (&async_tp);
1125 mono_mutex_lock (&wsqs_lock);
1126 mono_wsq_cleanup ();
1128 g_ptr_array_free (wsqs, TRUE);
1130 mono_mutex_unlock (&wsqs_lock);
1131 MONO_SEM_DESTROY (&async_tp.new_job);
1134 MONO_SEM_DESTROY (&monitor_sem);
1138 threadpool_start_thread (ThreadPool *tp)
1143 stack_size = (!tp->is_io) ? 0 : SMALL_STACK;
1144 while (!mono_runtime_is_shutting_down () && (n = tp->nthreads) < tp->max_threads) {
1145 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n) {
1146 #ifndef DISABLE_PERFCOUNTERS
1147 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
1149 mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE, stack_size);
1158 pulse_on_new_job (ThreadPool *tp)
1161 MONO_SEM_POST (&tp->new_job);
1165 threadpool_kill_thread (ThreadPool *tp)
1167 if (tp->destroy_thread == 0 && InterlockedCompareExchange (&tp->destroy_thread, 1, 0) == 0)
1168 pulse_on_new_job (tp);
1172 icall_append_job (MonoObject *ar)
1174 threadpool_append_jobs (&async_tp, &ar, 1);
1178 threadpool_append_job (ThreadPool *tp, MonoObject *ar)
1180 threadpool_append_jobs (tp, &ar, 1);
1184 threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs)
1189 if (mono_runtime_is_shutting_down ())
1192 if (tp->pool_status == 0 && InterlockedCompareExchange (&tp->pool_status, 1, 0) == 0) {
1194 monitor_internal_thread = mono_thread_create_internal (mono_get_root_domain (), monitor_thread, NULL, TRUE, SMALL_STACK);
1195 monitor_internal_thread->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
1196 threadpool_start_thread (tp);
1198 /* Create on demand up to min_threads to avoid startup penalty for apps that don't use
1199 * the threadpool that much
1201 if (mono_config_is_server_mode ()) {
1202 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, tp, TRUE, SMALL_STACK);
1206 InterlockedAdd (&monitor_njobs, njobs);
1208 if (monitor_state == MONITOR_STATE_SLEEPING && InterlockedCompareExchange (&monitor_state, MONITOR_STATE_AWAKE, MONITOR_STATE_SLEEPING) == MONITOR_STATE_SLEEPING)
1209 MONO_SEM_POST (&monitor_sem);
1211 if (monitor_state == MONITOR_STATE_FALLING_ASLEEP)
1212 InterlockedCompareExchange (&monitor_state, MONITOR_STATE_AWAKE, MONITOR_STATE_FALLING_ASLEEP);
1214 for (i = 0; i < njobs; i++) {
1216 if (ar == NULL || mono_domain_is_unloading (ar->vtable->domain))
1217 continue; /* Might happen when cleaning domain jobs */
1218 threadpool_jobs_inc (ar);
1219 #ifndef DISABLE_PERFCOUNTERS
1220 mono_perfcounter_update_value (tp->pc_nitems, TRUE, 1);
1222 if (!tp->is_io && mono_wsq_local_push (ar))
1225 mono_cq_enqueue (tp->queue, ar);
1229 InterlockedAdd (&tp->njobs, njobs);
1232 for (i = 0; tp->waiting > 0 && i < MIN(njobs, tp->max_threads); i++)
1233 pulse_on_new_job (tp);
1237 threadpool_clear_queue (ThreadPool *tp, MonoDomain *domain)
1240 MonoMList *other = NULL;
1241 MonoCQ *queue = tp->queue;
1246 while (mono_cq_dequeue (queue, &obj)) {
1249 if (obj->vtable->domain != domain)
1250 other = mono_mlist_prepend (other, obj);
1251 threadpool_jobs_dec (obj);
1254 if (mono_runtime_is_shutting_down ())
1258 threadpool_append_job (tp, (MonoObject *) mono_mlist_get_data (other));
1259 other = mono_mlist_next (other);
1264 remove_sockstate_for_domain (gpointer key, gpointer value, gpointer user_data)
1266 MonoMList *list = value;
1267 gboolean remove = FALSE;
1269 MonoObject *data = mono_mlist_get_data (list);
1270 if (mono_object_domain (data) == user_data) {
1272 mono_mlist_set_data (list, NULL);
1274 list = mono_mlist_next (list);
1276 //FIXME is there some sort of additional unregistration we need to perform here?
1281 * Clean up the threadpool of all domain jobs.
1282 * Can only be called as part of the domain unloading process as
1283 * it will wait for all jobs to be visible to the interruption code.
1286 mono_thread_pool_remove_domain_jobs (MonoDomain *domain, int timeout)
1290 guint32 start_time = 0;
1292 g_assert (domain->state == MONO_APPDOMAIN_UNLOADING);
1294 threadpool_clear_queue (&async_tp, domain);
1295 threadpool_clear_queue (&async_io_tp, domain);
1297 mono_mutex_lock (&socket_io_data.io_lock);
1298 if (socket_io_data.sock_to_state)
1299 mono_g_hash_table_foreach_remove (socket_io_data.sock_to_state, remove_sockstate_for_domain, domain);
1301 mono_mutex_unlock (&socket_io_data.io_lock);
1304 * There might be some threads out that could be about to execute stuff from the given domain.
1305 * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
1307 sem_handle = CreateSemaphore (NULL, 0, 1, NULL);
1309 domain->cleanup_semaphore = sem_handle;
1311 * The memory barrier here is required to have global ordering between assigning to cleanup_semaphone
1312 * and reading threadpool_jobs.
1313 * Otherwise this thread could read a stale version of threadpool_jobs and wait forever.
1315 mono_memory_write_barrier ();
1317 if (domain->threadpool_jobs && timeout != -1)
1318 start_time = mono_msec_ticks ();
1319 while (domain->threadpool_jobs) {
1320 WaitForSingleObject (sem_handle, timeout);
1321 if (timeout != -1 && (mono_msec_ticks () - start_time) > timeout) {
1327 domain->cleanup_semaphore = NULL;
1328 CloseHandle (sem_handle);
1333 threadpool_free_queue (ThreadPool *tp)
1335 mono_cq_destroy (tp->queue);
1340 mono_thread_pool_is_queue_array (MonoArray *o)
1342 // gpointer obj = o;
1344 // FIXME: need some fix in sgen code.
1354 mono_mutex_lock (&wsqs_lock);
1355 wsq = mono_wsq_create ();
1357 mono_mutex_unlock (&wsqs_lock);
1360 for (i = 0; i < wsqs->len; i++) {
1361 if (g_ptr_array_index (wsqs, i) == NULL) {
1362 wsqs->pdata [i] = wsq;
1363 mono_mutex_unlock (&wsqs_lock);
1367 g_ptr_array_add (wsqs, wsq);
1368 mono_mutex_unlock (&wsqs_lock);
1373 remove_wsq (MonoWSQ *wsq)
1380 mono_mutex_lock (&wsqs_lock);
1382 mono_mutex_unlock (&wsqs_lock);
1385 g_ptr_array_remove_fast (wsqs, wsq);
1388 * Only clean this up when shutting down, any other case will error out
1389 * if we're removing a queue that still has work items.
1391 if (mono_runtime_is_shutting_down ()) {
1392 while (mono_wsq_local_pop (&data)) {
1393 threadpool_jobs_dec (data);
1397 mono_wsq_destroy (wsq);
1398 mono_mutex_unlock (&wsqs_lock);
1402 try_steal (MonoWSQ *local_wsq, gpointer *data, gboolean retry)
1407 if (wsqs == NULL || data == NULL || *data != NULL)
1412 if (mono_runtime_is_shutting_down ())
1415 mono_mutex_lock (&wsqs_lock);
1416 for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
1419 wsq = wsqs->pdata [i];
1420 if (wsq == local_wsq || mono_wsq_count (wsq) == 0)
1422 mono_wsq_try_steal (wsqs->pdata [i], data, ms);
1423 if (*data != NULL) {
1424 mono_mutex_unlock (&wsqs_lock);
1428 mono_mutex_unlock (&wsqs_lock);
1430 } while (retry && ms < 11);
1434 dequeue_or_steal (ThreadPool *tp, gpointer *data, MonoWSQ *local_wsq)
1436 MonoCQ *queue = tp->queue;
1437 if (mono_runtime_is_shutting_down () || !queue)
1439 mono_cq_dequeue (queue, (MonoObject **) data);
1440 if (!tp->is_io && !*data)
1441 try_steal (local_wsq, data, FALSE);
1442 return (*data != NULL);
1446 should_i_die (ThreadPool *tp)
1448 gboolean result = FALSE;
1449 if (tp->destroy_thread == 1 && InterlockedCompareExchange (&tp->destroy_thread, 0, 1) == 1)
1450 result = (tp->nthreads > tp->min_threads);
1455 set_tp_thread_info (ThreadPool *tp)
1458 MonoInternalThread *thread = mono_thread_internal_current ();
1460 mono_profiler_thread_start (thread->tid);
1461 name = (tp->is_io) ? "IO Threadpool worker" : "Threadpool worker";
1462 mono_thread_set_name_internal (thread, mono_string_new (mono_domain_get (), name), FALSE);
1466 clear_thread_state (void)
1468 MonoInternalThread *thread = mono_thread_internal_current ();
1469 /* If the callee changes the background status, set it back to TRUE */
1470 mono_thread_clr_state (thread , ~ThreadState_Background);
1471 if (!mono_thread_test_state (thread , ThreadState_Background))
1472 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
1476 check_for_interruption_critical (void)
1478 MonoInternalThread *thread;
1479 /*RULE NUMBER ONE OF SKIP_THREAD: NEVER POKE MANAGED STATE.*/
1480 mono_gc_set_skip_thread (FALSE);
1482 thread = mono_thread_internal_current ();
1483 if (THREAD_WANTS_A_BREAK (thread))
1484 mono_thread_interruption_checkpoint ();
1486 /*RULE NUMBER TWO OF SKIP_THREAD: READ RULE NUMBER ONE.*/
1487 mono_gc_set_skip_thread (TRUE);
1491 fire_profiler_thread_end (void)
1493 MonoInternalThread *thread = mono_thread_internal_current ();
1494 mono_profiler_thread_end (thread->tid);
1498 async_invoke_thread (gpointer data)
1510 set_tp_thread_info (tp);
1513 tp_start_func (tp_hooks_user_data);
1517 MonoAsyncResult *ar;
1519 gboolean is_io_task;
1524 ar = (MonoAsyncResult *) data;
1526 InterlockedIncrement (&tp->busy_threads);
1527 domain = ((MonoObject *)ar)->vtable->domain;
1528 #ifndef DISABLE_SOCKETS
1529 klass = ((MonoObject *) data)->vtable->klass;
1530 is_io_task = !is_corlib_asyncresult (domain, klass);
1533 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1534 is_socket = is_socketasyncresult (domain, klass);
1536 switch (state->operation) {
1537 case AIO_OP_RECEIVE:
1538 state->total = ICALL_RECV (state);
1541 state->total = ICALL_SEND (state);
1546 /* worker threads invokes methods in different domains,
1547 * so we need to set the right domain here */
1550 if (mono_domain_is_unloading (domain) || mono_runtime_is_shutting_down ()) {
1551 threadpool_jobs_dec ((MonoObject *)ar);
1554 InterlockedDecrement (&tp->busy_threads);
1556 mono_thread_push_appdomain_ref (domain);
1557 if (threadpool_jobs_dec ((MonoObject *)ar)) {
1560 mono_thread_pop_appdomain_ref ();
1561 InterlockedDecrement (&tp->busy_threads);
1565 if (mono_domain_set (domain, FALSE)) {
1568 if (tp_item_begin_func)
1569 tp_item_begin_func (tp_item_user_data);
1571 exc = mono_async_invoke (tp, ar);
1572 if (tp_item_end_func)
1573 tp_item_end_func (tp_item_user_data);
1575 mono_internal_thread_unhandled_exception (exc);
1576 if (is_socket && tp->is_io) {
1577 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1579 if (state->completed && state->callback) {
1580 MonoAsyncResult *cb_ares;
1581 cb_ares = create_simple_asyncresult ((MonoObject *) state->callback,
1582 (MonoObject *) state);
1583 icall_append_job ((MonoObject *) cb_ares);
1586 mono_domain_set (mono_get_root_domain (), TRUE);
1588 mono_thread_pop_appdomain_ref ();
1589 InterlockedDecrement (&tp->busy_threads);
1590 clear_thread_state ();
1596 must_die = should_i_die (tp);
1598 mono_wsq_suspend (wsq);
1600 if (tp->is_io || !mono_wsq_local_pop (&data))
1601 dequeue_or_steal (tp, &data, wsq);
1605 while (!must_die && !data && n_naps < 4) {
1608 InterlockedIncrement (&tp->waiting);
1610 // Another thread may have added a job into its wsq since the last call to dequeue_or_steal
1611 // Check all the queues again before entering the wait loop
1612 dequeue_or_steal (tp, &data, wsq);
1614 InterlockedDecrement (&tp->waiting);
1618 mono_gc_set_skip_thread (TRUE);
1620 #if defined(__OpenBSD__)
1621 while (mono_cq_count (tp->queue) == 0 && (res = mono_sem_wait (&tp->new_job, TRUE)) == -1) {// && errno == EINTR) {
1623 while (mono_cq_count (tp->queue) == 0 && (res = mono_sem_timedwait (&tp->new_job, 2000, TRUE)) == -1) {// && errno == EINTR) {
1625 if (mono_runtime_is_shutting_down ())
1627 check_for_interruption_critical ();
1629 InterlockedDecrement (&tp->waiting);
1631 mono_gc_set_skip_thread (FALSE);
1633 if (mono_runtime_is_shutting_down ())
1635 must_die = should_i_die (tp);
1636 dequeue_or_steal (tp, &data, wsq);
1640 if (!data && !tp->is_io && !mono_runtime_is_shutting_down ()) {
1641 mono_wsq_local_pop (&data);
1642 if (data && must_die) {
1643 InterlockedCompareExchange (&tp->destroy_thread, 1, 0);
1644 pulse_on_new_job (tp);
1653 down = mono_runtime_is_shutting_down ();
1654 if (!down && nt <= tp->min_threads)
1656 if (down || InterlockedCompareExchange (&tp->nthreads, nt - 1, nt) == nt) {
1657 #ifndef DISABLE_PERFCOUNTERS
1658 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, -1);
1664 fire_profiler_thread_end ();
1667 tp_finish_func (tp_hooks_user_data);
1674 g_assert_not_reached ();
1678 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
1680 *workerThreads = async_tp.max_threads - async_tp.busy_threads;
1681 *completionPortThreads = async_io_tp.max_threads - async_io_tp.busy_threads;
1685 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
1687 *workerThreads = async_tp.max_threads;
1688 *completionPortThreads = async_io_tp.max_threads;
1692 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
1694 *workerThreads = async_tp.min_threads;
1695 *completionPortThreads = async_io_tp.min_threads;
1699 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
1702 gint max_io_threads;
1704 max_threads = async_tp.max_threads;
1705 if (workerThreads <= 0 || workerThreads > max_threads)
1708 max_io_threads = async_io_tp.max_threads;
1709 if (completionPortThreads <= 0 || completionPortThreads > max_io_threads)
1712 InterlockedExchange (&async_tp.min_threads, workerThreads);
1713 InterlockedExchange (&async_io_tp.min_threads, completionPortThreads);
1714 if (workerThreads > async_tp.nthreads)
1715 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_tp, TRUE, SMALL_STACK);
1716 if (completionPortThreads > async_io_tp.nthreads)
1717 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_io_tp, TRUE, SMALL_STACK);
1722 ves_icall_System_Threading_ThreadPool_SetMaxThreads (gint workerThreads, gint completionPortThreads)
1725 gint min_io_threads;
1728 cpu_count = mono_cpu_count ();
1729 min_threads = async_tp.min_threads;
1730 if (workerThreads < min_threads || workerThreads < cpu_count)
1733 /* We don't really have the concept of completion ports. Do we care here? */
1734 min_io_threads = async_io_tp.min_threads;
1735 if (completionPortThreads < min_io_threads || completionPortThreads < cpu_count)
1738 InterlockedExchange (&async_tp.max_threads, workerThreads);
1739 InterlockedExchange (&async_io_tp.max_threads, completionPortThreads);
1744 * mono_install_threadpool_thread_hooks
1745 * @start_func: the function to be called right after a new threadpool thread is created. Can be NULL.
1746 * @finish_func: the function to be called right before a thredpool thread is exiting. Can be NULL.
1747 * @user_data: argument passed to @start_func and @finish_func.
1749 * @start_fun will be called right after a threadpool thread is created and @finish_func right before a threadpool thread exits.
1750 * The calls will be made from the thread itself.
1753 mono_install_threadpool_thread_hooks (MonoThreadPoolFunc start_func, MonoThreadPoolFunc finish_func, gpointer user_data)
1755 tp_start_func = start_func;
1756 tp_finish_func = finish_func;
1757 tp_hooks_user_data = user_data;
1761 * mono_install_threadpool_item_hooks
1762 * @begin_func: the function to be called before a threadpool work item processing starts.
1763 * @end_func: the function to be called after a threadpool work item is finished.
1764 * @user_data: argument passed to @begin_func and @end_func.
1766 * The calls will be made from the thread itself and from the same AppDomain
1767 * where the work item was executed.
1771 mono_install_threadpool_item_hooks (MonoThreadPoolItemFunc begin_func, MonoThreadPoolItemFunc end_func, gpointer user_data)
1773 tp_item_begin_func = begin_func;
1774 tp_item_end_func = end_func;
1775 tp_item_user_data = user_data;
1779 mono_internal_thread_unhandled_exception (MonoObject* exc)
1781 if (mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_CURRENT) {
1785 klass = exc->vtable->klass;
1786 unloaded = is_appdomainunloaded_exception (exc->vtable->domain, klass);
1787 if (!unloaded && klass != mono_defaults.threadabortexception_class) {
1788 mono_unhandled_exception (exc);
1789 if (mono_environment_exitcode_get () == 1)
1792 if (klass == mono_defaults.threadabortexception_class)
1793 mono_thread_internal_reset_abort (mono_thread_internal_current ());
1798 * Suspend creation of new threads.
1801 mono_thread_pool_suspend (void)
1807 * Resume creation of new threads.
1810 mono_thread_pool_resume (void)