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 *threads;
162 mono_mutex_t threads_lock;
163 static GPtrArray *wsqs;
164 mono_mutex_t wsqs_lock;
165 static gboolean suspended;
167 static volatile gint32 monitor_njobs = 0;
168 static volatile gint32 monitor_state;
169 static MonoSemType monitor_sem;
170 static MonoInternalThread *monitor_internal_thread;
173 static MonoThreadPoolFunc tp_start_func;
174 static MonoThreadPoolFunc tp_finish_func;
175 static gpointer tp_hooks_user_data;
176 static MonoThreadPoolItemFunc tp_item_begin_func;
177 static MonoThreadPoolItemFunc tp_item_end_func;
178 static gpointer tp_item_user_data;
188 AIO_OP_RECV_JUST_CALLBACK,
189 AIO_OP_SEND_JUST_CALLBACK,
193 AIO_OP_ACCEPTRECEIVE,
194 AIO_OP_RECEIVE_BUFFERS,
199 #include <mono/metadata/tpool-poll.c>
201 #include <mono/metadata/tpool-epoll.c>
202 #elif defined(USE_KQUEUE_FOR_THREADPOOL)
203 #include <mono/metadata/tpool-kqueue.c>
206 * Functions to check whenever a class is given system class. We need to cache things in MonoDomain since some of the
207 * assemblies can be unloaded.
211 is_system_type (MonoDomain *domain, MonoClass *klass)
213 if (domain->system_image == NULL)
214 domain->system_image = mono_image_loaded ("System");
216 return klass->image == domain->system_image;
220 is_corlib_type (MonoDomain *domain, MonoClass *klass)
222 return klass->image == mono_defaults.corlib;
226 * Note that we call it is_socket_type() where 'socket' refers to the image
227 * that contains the System.Net.Sockets.Socket type.
230 is_socket_type (MonoDomain *domain, MonoClass *klass)
232 return is_system_type (domain, klass);
235 #define check_type_cached(domain, ASSEMBLY, _class, _namespace, _name, loc) do { \
237 return *loc == _class; \
238 if (is_##ASSEMBLY##_type (domain, _class) && !strcmp (_name, _class->name) && !strcmp (_namespace, _class->name_space)) { \
245 #define check_corlib_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, corlib, _class, _namespace, _name, loc)
247 #define check_socket_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, socket, _class, _namespace, _name, loc)
249 #define check_system_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, system, _class, _namespace, _name, loc)
252 is_corlib_asyncresult (MonoDomain *domain, MonoClass *klass)
254 check_corlib_type_cached (domain, klass, "System.Runtime.Remoting.Messaging", "AsyncResult", &domain->corlib_asyncresult_class);
258 is_socket (MonoDomain *domain, MonoClass *klass)
260 check_socket_type_cached (domain, klass, "System.Net.Sockets", "Socket", &domain->socket_class);
264 is_socketasyncresult (MonoDomain *domain, MonoClass *klass)
266 return (klass->nested_in &&
267 is_socket (domain, klass->nested_in) &&
268 !strcmp (klass->name, "SocketAsyncResult"));
272 is_socketasynccall (MonoDomain *domain, MonoClass *klass)
274 return (klass->nested_in &&
275 is_socket (domain, klass->nested_in) &&
276 !strcmp (klass->name, "SocketAsyncCall"));
280 is_appdomainunloaded_exception (MonoDomain *domain, MonoClass *klass)
282 check_corlib_type_cached (domain, klass, "System", "AppDomainUnloadedException", &domain->ad_unloaded_ex_class);
286 is_sd_process (MonoDomain *domain, MonoClass *klass)
288 check_system_type_cached (domain, klass, "System.Diagnostics", "Process", &domain->process_class);
292 is_sdp_asyncreadhandler (MonoDomain *domain, MonoClass *klass)
295 return (klass->nested_in &&
296 is_sd_process (domain, klass->nested_in) &&
297 !strcmp (klass->name, "AsyncReadHandler"));
301 #ifdef DISABLE_SOCKETS
303 #define socket_io_cleanup(x)
306 get_event_from_state (MonoSocketAsyncResult *state)
308 g_assert_not_reached ();
313 get_events_from_list (MonoMList *list)
321 socket_io_cleanup (SocketIOData *data)
323 mono_mutex_lock (&data->io_lock);
324 if (data->inited != 2) {
325 mono_mutex_unlock (&data->io_lock);
329 data->shutdown (data->event_data);
330 mono_mutex_unlock (&data->io_lock);
334 get_event_from_state (MonoSocketAsyncResult *state)
336 switch (state->operation) {
339 case AIO_OP_RECV_JUST_CALLBACK:
340 case AIO_OP_RECEIVEFROM:
341 case AIO_OP_READPIPE:
342 case AIO_OP_ACCEPTRECEIVE:
343 case AIO_OP_RECEIVE_BUFFERS:
346 case AIO_OP_SEND_JUST_CALLBACK:
349 case AIO_OP_SEND_BUFFERS:
350 case AIO_OP_DISCONNECT:
352 default: /* Should never happen */
353 g_message ("get_event_from_state: unknown value in switch!!!");
359 get_events_from_list (MonoMList *list)
361 MonoSocketAsyncResult *state;
364 while (list && (state = (MonoSocketAsyncResult *)mono_mlist_get_data (list))) {
365 events |= get_event_from_state (state);
366 list = mono_mlist_next (list);
372 #define ICALL_RECV(x) ves_icall_System_Net_Sockets_Socket_Receive_internal (\
373 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
374 x->socket_flags, &x->error);
376 #define ICALL_SEND(x) ves_icall_System_Net_Sockets_Socket_Send_internal (\
377 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
378 x->socket_flags, &x->error);
380 #endif /* !DISABLE_SOCKETS */
383 threadpool_jobs_inc (MonoObject *obj)
386 InterlockedIncrement (&obj->vtable->domain->threadpool_jobs);
390 threadpool_jobs_dec (MonoObject *obj)
398 domain = obj->vtable->domain;
399 remaining_jobs = InterlockedDecrement (&domain->threadpool_jobs);
400 if (remaining_jobs == 0 && domain->cleanup_semaphore) {
401 ReleaseSemaphore (domain->cleanup_semaphore, 1, NULL);
408 get_io_event (MonoMList **list, gint event)
418 state = mono_mlist_get_data (current);
419 if (get_event_from_state ((MonoSocketAsyncResult *) state) == event)
424 current = mono_mlist_next (current);
429 mono_mlist_set_next (prev, mono_mlist_next (current));
431 *list = mono_mlist_next (*list);
439 * select/poll wake up when a socket is closed, but epoll just removes
440 * the socket from its internal list without notification.
443 mono_thread_pool_remove_socket (int sock)
446 MonoSocketAsyncResult *state;
449 if (socket_io_data.inited == 0)
452 mono_mutex_lock (&socket_io_data.io_lock);
453 if (socket_io_data.sock_to_state == NULL) {
454 mono_mutex_unlock (&socket_io_data.io_lock);
457 list = mono_g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
459 mono_g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
460 mono_mutex_unlock (&socket_io_data.io_lock);
463 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
464 if (state->operation == AIO_OP_RECEIVE)
465 state->operation = AIO_OP_RECV_JUST_CALLBACK;
466 else if (state->operation == AIO_OP_SEND)
467 state->operation = AIO_OP_SEND_JUST_CALLBACK;
469 ares = get_io_event (&list, MONO_POLLIN);
470 threadpool_append_job (&async_io_tp, ares);
472 ares = get_io_event (&list, MONO_POLLOUT);
473 threadpool_append_job (&async_io_tp, ares);
479 init_event_system (SocketIOData *data)
482 if (data->event_system == EPOLL_BACKEND) {
483 data->event_data = tp_epoll_init (data);
484 if (data->event_data == NULL) {
485 if (g_getenv ("MONO_DEBUG"))
486 g_message ("Falling back to poll()");
487 data->event_system = POLL_BACKEND;
490 #elif defined(USE_KQUEUE_FOR_THREADPOOL)
491 if (data->event_system == KQUEUE_BACKEND)
492 data->event_data = tp_kqueue_init (data);
494 if (data->event_system == POLL_BACKEND)
495 data->event_data = tp_poll_init (data);
499 socket_io_init (SocketIOData *data)
503 if (data->inited >= 2) // 2 -> initialized, 3-> cleaned up
506 inited = InterlockedCompareExchange (&data->inited, 1, 0);
509 if (data->inited >= 2)
515 mono_mutex_lock (&data->io_lock);
516 data->sock_to_state = mono_g_hash_table_new_type (g_direct_hash, g_direct_equal, MONO_HASH_VALUE_GC);
518 data->event_system = EPOLL_BACKEND;
519 #elif defined(USE_KQUEUE_FOR_THREADPOOL)
520 data->event_system = KQUEUE_BACKEND;
522 data->event_system = POLL_BACKEND;
524 if (g_getenv ("MONO_DISABLE_AIO") != NULL)
525 data->event_system = POLL_BACKEND;
527 init_event_system (data);
528 mono_thread_create_internal (mono_get_root_domain (), data->wait, data, TRUE, SMALL_STACK);
529 mono_mutex_unlock (&data->io_lock);
531 threadpool_start_thread (&async_io_tp);
535 socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
538 SocketIOData *data = &socket_io_data;
543 socket_io_init (&socket_io_data);
544 if (mono_runtime_is_shutting_down () || data->inited == 3 || data->sock_to_state == NULL)
546 if (async_tp.pool_status == 2)
549 MONO_OBJECT_SETREF (state, ares, ares);
551 fd = GPOINTER_TO_INT (state->handle);
552 mono_mutex_lock (&data->io_lock);
553 if (data->sock_to_state == NULL) {
554 mono_mutex_unlock (&data->io_lock);
557 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
559 list = mono_mlist_alloc ((MonoObject*)state);
562 list = mono_mlist_append (list, (MonoObject*)state);
566 mono_g_hash_table_replace (data->sock_to_state, state->handle, list);
567 ievt = get_events_from_list (list);
568 /* The modify function leaves the io_lock critical section. */
569 data->modify (data, fd, state->operation, ievt, is_new);
572 #ifndef DISABLE_SOCKETS
574 socket_io_filter (MonoObject *target, MonoObject *state)
577 MonoSocketAsyncResult *sock_res;
581 if (target == NULL || state == NULL)
584 domain = target->vtable->domain;
585 klass = target->vtable->klass;
586 if (socket_async_call_klass == NULL && is_socketasynccall (domain, klass))
587 socket_async_call_klass = klass;
589 if (process_async_call_klass == NULL && is_sdp_asyncreadhandler (domain, klass))
590 process_async_call_klass = klass;
592 if (klass != socket_async_call_klass && klass != process_async_call_klass)
595 sock_res = (MonoSocketAsyncResult *) state;
596 op = sock_res->operation;
597 if (op < AIO_OP_FIRST || op >= AIO_OP_LAST)
602 #endif /* !DISABLE_SOCKETS */
604 /* Returns the exception thrown when invoking, if any */
606 mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares)
608 ASyncCall *ac = (ASyncCall *)ares->object_data;
609 MonoObject *res, *exc = NULL;
610 MonoArray *out_args = NULL;
611 HANDLE wait_event = NULL;
612 MonoInternalThread *thread = mono_thread_internal_current ();
614 if (ares->execution_context) {
615 /* use captured ExecutionContext (if available) */
616 MONO_OBJECT_SETREF (ares, original_context, mono_thread_get_execution_context ());
617 mono_thread_set_execution_context (ares->execution_context);
619 ares->original_context = NULL;
623 /* Fast path from ThreadPool.*QueueUserWorkItem */
624 void *pa = ares->async_state;
625 /* The debugger needs this */
626 thread->async_invoke_method = ((MonoDelegate*)ares->async_delegate)->method;
627 res = mono_runtime_delegate_invoke (ares->async_delegate, &pa, &exc);
628 thread->async_invoke_method = NULL;
630 MonoObject *cb_exc = NULL;
633 res = mono_message_invoke (ares->async_delegate, ac->msg, &exc, &out_args);
634 MONO_OBJECT_SETREF (ac, res, res);
635 MONO_OBJECT_SETREF (ac, msg->exc, exc);
636 MONO_OBJECT_SETREF (ac, out_args, out_args);
638 mono_monitor_enter ((MonoObject *) ares);
640 if (ares->handle != NULL)
641 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
642 mono_monitor_exit ((MonoObject *) ares);
643 /* notify listeners */
644 if (wait_event != NULL)
645 SetEvent (wait_event);
647 /* call async callback if cb_method != null*/
648 if (ac != NULL && ac->cb_method) {
651 thread->async_invoke_method = ac->cb_method;
652 mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &cb_exc);
653 thread->async_invoke_method = NULL;
660 /* restore original thread execution context if flow isn't suppressed, i.e. non null */
661 if (ares->original_context) {
662 mono_thread_set_execution_context (ares->original_context);
663 ares->original_context = NULL;
667 InterlockedDecrement (&tp->njobs);
670 InterlockedIncrement (&tp->nexecuted);
672 if (InterlockedDecrement (&monitor_njobs) == 0)
673 monitor_state = MONITOR_STATE_FALLING_ASLEEP;
679 threadpool_start_idle_threads (ThreadPool *tp)
684 stack_size = (!tp->is_io) ? 0 : SMALL_STACK;
688 if (n >= tp->min_threads)
690 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n)
693 #ifndef DISABLE_PERFCOUNTERS
694 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
696 mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE, stack_size);
702 threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer))
704 memset (tp, 0, sizeof (ThreadPool));
705 tp->min_threads = min_threads;
706 tp->max_threads = max_threads;
707 tp->async_invoke = async_invoke;
708 tp->queue = mono_cq_create ();
709 MONO_SEM_INIT (&tp->new_job, 0);
712 #ifndef DISABLE_PERFCOUNTERS
714 init_perf_counter (const char *category, const char *counter)
716 MonoString *category_str;
717 MonoString *counter_str;
723 if (category == NULL || counter == NULL)
725 root = mono_get_root_domain ();
726 category_str = mono_string_new (root, category);
727 counter_str = mono_string_new (root, counter);
728 machine = mono_string_new (root, ".");
729 return mono_perfcounter_get_impl (category_str, counter_str, NULL, machine, &type, &custom);
735 print_pool_info (ThreadPool *tp)
738 // if (tp->tail - tp->head == 0)
741 g_print ("Pool status? %d\n", InterlockedCompareExchange (&tp->pool_status, 0, 0));
742 g_print ("Min. threads: %d\n", InterlockedCompareExchange (&tp->min_threads, 0, 0));
743 g_print ("Max. threads: %d\n", InterlockedCompareExchange (&tp->max_threads, 0, 0));
744 g_print ("nthreads: %d\n", InterlockedCompareExchange (&tp->nthreads, 0, 0));
745 g_print ("busy threads: %d\n", InterlockedCompareExchange (&tp->busy_threads, 0, 0));
746 g_print ("Waiting: %d\n", InterlockedCompareExchange (&tp->waiting, 0, 0));
747 g_print ("Queued: %d\n", (tp->tail - tp->head));
748 if (tp == &async_tp) {
750 mono_mutex_lock (&wsqs_lock);
751 for (i = 0; i < wsqs->len; i++) {
752 g_print ("\tWSQ %d: %d\n", i, mono_wsq_count (g_ptr_array_index (wsqs, i)));
754 mono_mutex_unlock (&wsqs_lock);
756 g_print ("\tSockets: %d\n", mono_g_hash_table_size (socket_io_data.sock_to_state));
758 g_print ("-------------\n");
762 signal_handler (int signo)
767 g_print ("\n-----Non-IO-----\n");
768 print_pool_info (tp);
770 g_print ("\n-----IO-----\n");
771 print_pool_info (tp);
776 #define SAMPLES_PERIOD 500
777 #define HISTORY_SIZE 10
778 /* number of iteration without any jobs
779 in the queue before going to sleep */
780 #define NUM_WAITING_ITERATIONS 10
789 monitor_heuristic (gint16 *current, gint16 *history_size, SamplesHistory *history, ThreadPool *tp)
794 gboolean all_waitsleepjoin;
795 MonoInternalThread *thread;
798 * The following heuristic tries to approach the optimal number of threads to maximize jobs throughput. To
799 * achieve this, it simply stores the number of jobs executed (nexecuted), the number of Threads (nthreads)
800 * and the decision (nthreads_diff) for the past HISTORY_SIZE periods of time, each period being of
801 * duration SAMPLES_PERIOD ms. This history gives us an insight into what happened, and to see if we should
802 * increase or reduce the number of threads by comparing the last period (current) to the best one.
804 * The algorithm can be describe as following :
805 * - if we have a better throughput than the best period : we should either increase the number of threads
806 * in case we already have more threads, either reduce the number of threads if we have less threads; this
807 * is equivalent to move away from the number of threads of the best period, because we are currently better
808 * - if we have a worse throughput than the best period : we should either decrease the number of threads if
809 * we have more threads, either increase the number of threads if we have less threads; this is equivalent
810 * to get closer to the number of threads of the best period, because we are currently worse
813 *history_size = MIN (*history_size + 1, HISTORY_SIZE);
814 cur = *current = (*current + 1) % *history_size;
816 history [cur].nthreads = tp->nthreads;
817 history [cur].nexecuted = InterlockedExchange (&tp->nexecuted, 0);
820 /* if we have waiting thread in the pool, then do not create a new one */
821 history [cur].nthreads_diff = tp->waiting > 1 ? -1 : 0;
823 } else if (tp->nthreads < tp->min_threads) {
824 history [cur].nthreads_diff = 1;
826 } else if (*history_size <= 1) {
827 /* first iteration, let's add a thread by default */
828 history [cur].nthreads_diff = 1;
831 mono_mutex_lock (&threads_lock);
832 all_waitsleepjoin = TRUE;
833 for (i = 0; i < threads->len; ++i) {
834 thread = g_ptr_array_index (threads, i);
835 if (!(thread->state & ThreadState_WaitSleepJoin)) {
836 all_waitsleepjoin = FALSE;
840 mono_mutex_unlock (&threads_lock);
842 if (all_waitsleepjoin) {
843 /* we might be in a condition of starvation/deadlock with tasks waiting for each others */
844 history [cur].nthreads_diff = 1;
847 max = cur == 0 ? 1 : 0;
848 for (i = 0; i < *history_size; i++) {
851 if (history [i].nexecuted > history [max].nexecuted)
855 if (history [cur].nexecuted >= history [max].nexecuted) {
856 /* we improved the situation, let's continue ! */
857 history [cur].nthreads_diff = history [cur].nthreads >= history [max].nthreads ? 1 : -1;
860 /* we made it worse, let's return to previous situation */
861 history [cur].nthreads_diff = history [cur].nthreads >= history [max].nthreads ? -1 : 1;
868 printf ("monitor_thread: decision: %1d, history [current]: {nexecuted: %5d, nthreads: %3d, waiting: %2d, nthreads_diff: %2d}, history [max]: {nexecuted: %5d, nthreads: %3d}\n",
869 decision, history [cur].nexecuted, history [cur].nthreads, tp->waiting, history [cur].nthreads_diff, history [max].nexecuted, history [max].nthreads);
872 return history [cur].nthreads_diff;
876 monitor_thread (gpointer unused)
878 ThreadPool *pools [2];
879 MonoInternalThread *thread;
883 gint8 num_waiting_iterations = 0;
885 gint16 history_size = 0, current = -1;
886 SamplesHistory *history = malloc (sizeof (SamplesHistory) * HISTORY_SIZE);
888 pools [0] = &async_tp;
889 pools [1] = &async_io_tp;
890 thread = mono_thread_internal_current ();
891 ves_icall_System_Threading_Thread_SetName_internal (thread, mono_string_new (mono_domain_get (), "Threadpool monitor"));
894 i = 10; //number of spurious awakes we tolerate before doing a round of rebalancing.
897 ts = mono_msec_ticks ();
898 if (SleepEx (ms, TRUE) == 0)
900 ms -= (mono_msec_ticks () - ts);
901 if (mono_runtime_is_shutting_down ())
903 if (THREAD_WANTS_A_BREAK (thread))
904 mono_thread_interruption_checkpoint ();
905 } while (ms > 0 && i--);
907 if (mono_runtime_is_shutting_down ())
913 switch (monitor_state) {
914 case MONITOR_STATE_AWAKE:
915 num_waiting_iterations = 0;
917 case MONITOR_STATE_FALLING_ASLEEP:
918 if (++num_waiting_iterations == NUM_WAITING_ITERATIONS) {
919 if (monitor_state == MONITOR_STATE_FALLING_ASLEEP && InterlockedCompareExchange (&monitor_state, MONITOR_STATE_SLEEPING, MONITOR_STATE_FALLING_ASLEEP) == MONITOR_STATE_FALLING_ASLEEP) {
920 MONO_SEM_WAIT (&monitor_sem);
922 num_waiting_iterations = 0;
928 case MONITOR_STATE_SLEEPING:
929 g_assert_not_reached ();
932 for (i = 0; i < 2; i++) {
937 if (!tp->waiting && mono_cq_count (tp->queue) > 0)
938 threadpool_start_thread (tp);
940 gint8 nthreads_diff = monitor_heuristic (¤t, &history_size, history, tp);
942 if (nthreads_diff > 0)
943 threadpool_start_thread (tp);
944 else if (nthreads_diff < 0)
945 threadpool_kill_thread (tp);
952 mono_thread_pool_init_tls (void)
958 mono_thread_pool_init (void)
960 gint threads_per_cpu = 1;
962 gint cpu_count = mono_cpu_count ();
968 result = InterlockedCompareExchange (&tp_inited, 1, 0);
977 MONO_GC_REGISTER_ROOT_FIXED (socket_io_data.sock_to_state);
978 mono_mutex_init_recursive (&socket_io_data.io_lock);
979 if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
980 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
981 if (threads_per_cpu < 1)
985 thread_count = MIN (cpu_count * threads_per_cpu, 100 * cpu_count);
986 threadpool_init (&async_tp, thread_count, MAX (100 * cpu_count, thread_count), async_invoke_thread);
987 threadpool_init (&async_io_tp, cpu_count * 2, cpu_count * 4, async_invoke_thread);
988 async_io_tp.is_io = TRUE;
990 async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
991 g_assert (async_call_klass);
993 mono_mutex_init (&threads_lock);
994 threads = g_ptr_array_sized_new (thread_count);
996 mono_mutex_init_recursive (&wsqs_lock);
997 wsqs = g_ptr_array_sized_new (MAX (100 * cpu_count, thread_count));
999 #ifndef DISABLE_PERFCOUNTERS
1000 async_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "Work Items Added");
1001 g_assert (async_tp.pc_nitems);
1003 async_io_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "IO Work Items Added");
1004 g_assert (async_io_tp.pc_nitems);
1006 async_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of Threads");
1007 g_assert (async_tp.pc_nthreads);
1009 async_io_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of IO Threads");
1010 g_assert (async_io_tp.pc_nthreads);
1014 signal (SIGALRM, signal_handler);
1018 MONO_SEM_INIT (&monitor_sem, 0);
1019 monitor_state = MONITOR_STATE_AWAKE;
1023 static MonoAsyncResult *
1024 create_simple_asyncresult (MonoObject *target, MonoObject *state)
1026 MonoDomain *domain = mono_domain_get ();
1027 MonoAsyncResult *ares;
1029 /* Don't call mono_async_result_new() to avoid capturing the context */
1030 ares = (MonoAsyncResult *) mono_object_new (domain, mono_defaults.asyncresult_class);
1031 MONO_OBJECT_SETREF (ares, async_delegate, target);
1032 MONO_OBJECT_SETREF (ares, async_state, state);
1037 icall_append_io_job (MonoObject *target, MonoSocketAsyncResult *state)
1039 MonoAsyncResult *ares;
1041 ares = create_simple_asyncresult (target, (MonoObject *) state);
1042 socket_io_add (ares, state);
1046 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
1049 MonoDomain *domain = mono_domain_get ();
1050 MonoAsyncResult *ares;
1053 ac = (ASyncCall*)mono_object_new (domain, async_call_klass);
1054 MONO_OBJECT_SETREF (ac, msg, msg);
1055 MONO_OBJECT_SETREF (ac, state, state);
1057 if (async_callback) {
1058 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
1059 MONO_OBJECT_SETREF (ac, cb_target, async_callback);
1062 ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
1063 MONO_OBJECT_SETREF (ares, async_delegate, target);
1065 #ifndef DISABLE_SOCKETS
1066 if (socket_io_filter (target, state)) {
1067 socket_io_add (ares, (MonoSocketAsyncResult *) state);
1071 threadpool_append_job (&async_tp, (MonoObject *) ares);
1076 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1084 /* check if already finished */
1085 mono_monitor_enter ((MonoObject *) ares);
1087 if (ares->endinvoke_called) {
1088 *exc = (MonoObject *) mono_get_exception_invalid_operation (NULL);
1089 mono_monitor_exit ((MonoObject *) ares);
1093 ares->endinvoke_called = 1;
1094 /* wait until we are really finished */
1095 if (!ares->completed) {
1096 if (ares->handle == NULL) {
1097 wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1098 g_assert(wait_event != 0);
1099 MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), wait_event));
1101 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
1103 mono_monitor_exit ((MonoObject *) ares);
1104 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
1106 mono_monitor_exit ((MonoObject *) ares);
1109 ac = (ASyncCall *) ares->object_data;
1110 g_assert (ac != NULL);
1111 *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1112 *out_args = ac->out_args;
1118 threadpool_kill_idle_threads (ThreadPool *tp)
1122 n = (gint) InterlockedCompareExchange (&tp->max_threads, 0, -1);
1125 MONO_SEM_POST (&tp->new_job);
1130 mono_thread_pool_cleanup (void)
1132 if (InterlockedExchange (&async_io_tp.pool_status, 2) == 1) {
1133 socket_io_cleanup (&socket_io_data); /* Empty when DISABLE_SOCKETS is defined */
1134 threadpool_kill_idle_threads (&async_io_tp);
1137 if (async_io_tp.queue != NULL) {
1138 MONO_SEM_DESTROY (&async_io_tp.new_job);
1139 threadpool_free_queue (&async_io_tp);
1143 if (InterlockedExchange (&async_tp.pool_status, 2) == 1) {
1144 threadpool_kill_idle_threads (&async_tp);
1145 threadpool_free_queue (&async_tp);
1149 mono_mutex_lock (&threads_lock);
1151 g_ptr_array_free (threads, FALSE);
1153 mono_mutex_unlock (&threads_lock);
1157 mono_mutex_lock (&wsqs_lock);
1158 mono_wsq_cleanup ();
1160 g_ptr_array_free (wsqs, TRUE);
1162 mono_mutex_unlock (&wsqs_lock);
1163 MONO_SEM_DESTROY (&async_tp.new_job);
1166 MONO_SEM_DESTROY (&monitor_sem);
1170 threadpool_start_thread (ThreadPool *tp)
1174 MonoInternalThread *thread;
1176 stack_size = (!tp->is_io) ? 0 : SMALL_STACK;
1177 while (!mono_runtime_is_shutting_down () && (n = tp->nthreads) < tp->max_threads) {
1178 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n) {
1179 #ifndef DISABLE_PERFCOUNTERS
1180 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
1182 thread = mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE, stack_size);
1184 mono_mutex_lock (&threads_lock);
1185 g_ptr_array_add (threads, thread);
1186 mono_mutex_unlock (&threads_lock);
1196 pulse_on_new_job (ThreadPool *tp)
1199 MONO_SEM_POST (&tp->new_job);
1203 threadpool_kill_thread (ThreadPool *tp)
1205 if (tp->destroy_thread == 0 && InterlockedCompareExchange (&tp->destroy_thread, 1, 0) == 0)
1206 pulse_on_new_job (tp);
1210 icall_append_job (MonoObject *ar)
1212 threadpool_append_jobs (&async_tp, &ar, 1);
1216 threadpool_append_job (ThreadPool *tp, MonoObject *ar)
1218 threadpool_append_jobs (tp, &ar, 1);
1222 threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs)
1227 if (mono_runtime_is_shutting_down ())
1230 if (tp->pool_status == 0 && InterlockedCompareExchange (&tp->pool_status, 1, 0) == 0) {
1232 monitor_internal_thread = mono_thread_create_internal (mono_get_root_domain (), monitor_thread, NULL, TRUE, SMALL_STACK);
1233 monitor_internal_thread->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
1234 threadpool_start_thread (tp);
1236 /* Create on demand up to min_threads to avoid startup penalty for apps that don't use
1237 * the threadpool that much
1239 if (mono_config_is_server_mode ()) {
1240 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, tp, TRUE, SMALL_STACK);
1244 InterlockedAdd (&monitor_njobs, njobs);
1246 if (monitor_state == MONITOR_STATE_SLEEPING && InterlockedCompareExchange (&monitor_state, MONITOR_STATE_AWAKE, MONITOR_STATE_SLEEPING) == MONITOR_STATE_SLEEPING)
1247 MONO_SEM_POST (&monitor_sem);
1249 if (monitor_state == MONITOR_STATE_FALLING_ASLEEP)
1250 InterlockedCompareExchange (&monitor_state, MONITOR_STATE_AWAKE, MONITOR_STATE_FALLING_ASLEEP);
1252 for (i = 0; i < njobs; i++) {
1254 if (ar == NULL || mono_domain_is_unloading (ar->vtable->domain))
1255 continue; /* Might happen when cleaning domain jobs */
1256 threadpool_jobs_inc (ar);
1257 #ifndef DISABLE_PERFCOUNTERS
1258 mono_perfcounter_update_value (tp->pc_nitems, TRUE, 1);
1260 if (!tp->is_io && mono_wsq_local_push (ar))
1263 mono_cq_enqueue (tp->queue, ar);
1267 InterlockedAdd (&tp->njobs, njobs);
1270 for (i = 0; tp->waiting > 0 && i < MIN(njobs, tp->max_threads); i++)
1271 pulse_on_new_job (tp);
1275 threadpool_clear_queue (ThreadPool *tp, MonoDomain *domain)
1278 MonoMList *other = NULL;
1279 MonoCQ *queue = tp->queue;
1284 while (mono_cq_dequeue (queue, &obj)) {
1287 if (obj->vtable->domain != domain)
1288 other = mono_mlist_prepend (other, obj);
1289 threadpool_jobs_dec (obj);
1292 if (mono_runtime_is_shutting_down ())
1296 threadpool_append_job (tp, (MonoObject *) mono_mlist_get_data (other));
1297 other = mono_mlist_next (other);
1302 remove_sockstate_for_domain (gpointer key, gpointer value, gpointer user_data)
1304 MonoMList *list = value;
1305 gboolean remove = FALSE;
1307 MonoObject *data = mono_mlist_get_data (list);
1308 if (mono_object_domain (data) == user_data) {
1310 mono_mlist_set_data (list, NULL);
1312 list = mono_mlist_next (list);
1314 //FIXME is there some sort of additional unregistration we need to perform here?
1319 * Clean up the threadpool of all domain jobs.
1320 * Can only be called as part of the domain unloading process as
1321 * it will wait for all jobs to be visible to the interruption code.
1324 mono_thread_pool_remove_domain_jobs (MonoDomain *domain, int timeout)
1328 guint32 start_time = 0;
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 WaitForSingleObject (sem_handle, timeout);
1359 if (timeout != -1 && (mono_msec_ticks () - start_time) > timeout) {
1365 domain->cleanup_semaphore = NULL;
1366 CloseHandle (sem_handle);
1371 threadpool_free_queue (ThreadPool *tp)
1373 mono_cq_destroy (tp->queue);
1378 mono_thread_pool_is_queue_array (MonoArray *o)
1380 // gpointer obj = o;
1382 // FIXME: need some fix in sgen code.
1392 mono_mutex_lock (&wsqs_lock);
1393 wsq = mono_wsq_create ();
1395 mono_mutex_unlock (&wsqs_lock);
1398 for (i = 0; i < wsqs->len; i++) {
1399 if (g_ptr_array_index (wsqs, i) == NULL) {
1400 wsqs->pdata [i] = wsq;
1401 mono_mutex_unlock (&wsqs_lock);
1405 g_ptr_array_add (wsqs, wsq);
1406 mono_mutex_unlock (&wsqs_lock);
1411 remove_wsq (MonoWSQ *wsq)
1418 mono_mutex_lock (&wsqs_lock);
1420 mono_mutex_unlock (&wsqs_lock);
1423 g_ptr_array_remove_fast (wsqs, wsq);
1426 * Only clean this up when shutting down, any other case will error out
1427 * if we're removing a queue that still has work items.
1429 if (mono_runtime_is_shutting_down ()) {
1430 while (mono_wsq_local_pop (&data)) {
1431 threadpool_jobs_dec (data);
1435 mono_wsq_destroy (wsq);
1436 mono_mutex_unlock (&wsqs_lock);
1440 try_steal (MonoWSQ *local_wsq, gpointer *data, gboolean retry)
1445 if (wsqs == NULL || data == NULL || *data != NULL)
1450 if (mono_runtime_is_shutting_down ())
1453 mono_mutex_lock (&wsqs_lock);
1454 for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
1457 wsq = wsqs->pdata [i];
1458 if (wsq == local_wsq || mono_wsq_count (wsq) == 0)
1460 mono_wsq_try_steal (wsqs->pdata [i], data, ms);
1461 if (*data != NULL) {
1462 mono_mutex_unlock (&wsqs_lock);
1466 mono_mutex_unlock (&wsqs_lock);
1468 } while (retry && ms < 11);
1472 dequeue_or_steal (ThreadPool *tp, gpointer *data, MonoWSQ *local_wsq)
1474 MonoCQ *queue = tp->queue;
1475 if (mono_runtime_is_shutting_down () || !queue)
1477 mono_cq_dequeue (queue, (MonoObject **) data);
1478 if (!tp->is_io && !*data)
1479 try_steal (local_wsq, data, FALSE);
1480 return (*data != NULL);
1484 should_i_die (ThreadPool *tp)
1486 gboolean result = FALSE;
1487 if (tp->destroy_thread == 1 && InterlockedCompareExchange (&tp->destroy_thread, 0, 1) == 1)
1488 result = (tp->nthreads > tp->min_threads);
1493 set_tp_thread_info (ThreadPool *tp)
1496 MonoInternalThread *thread = mono_thread_internal_current ();
1498 mono_profiler_thread_start (thread->tid);
1499 name = (tp->is_io) ? "IO Threadpool worker" : "Threadpool worker";
1500 mono_thread_set_name_internal (thread, mono_string_new (mono_domain_get (), name), FALSE);
1504 clear_thread_state (void)
1506 MonoInternalThread *thread = mono_thread_internal_current ();
1507 /* If the callee changes the background status, set it back to TRUE */
1508 mono_thread_clr_state (thread , ~ThreadState_Background);
1509 if (!mono_thread_test_state (thread , ThreadState_Background))
1510 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
1514 check_for_interruption_critical (void)
1516 MonoInternalThread *thread;
1517 /*RULE NUMBER ONE OF SKIP_THREAD: NEVER POKE MANAGED STATE.*/
1518 mono_gc_set_skip_thread (FALSE);
1520 thread = mono_thread_internal_current ();
1521 if (THREAD_WANTS_A_BREAK (thread))
1522 mono_thread_interruption_checkpoint ();
1524 /*RULE NUMBER TWO OF SKIP_THREAD: READ RULE NUMBER ONE.*/
1525 mono_gc_set_skip_thread (TRUE);
1529 fire_profiler_thread_end (void)
1531 MonoInternalThread *thread = mono_thread_internal_current ();
1532 mono_profiler_thread_end (thread->tid);
1536 async_invoke_thread (gpointer data)
1548 set_tp_thread_info (tp);
1551 tp_start_func (tp_hooks_user_data);
1555 MonoAsyncResult *ar;
1557 gboolean is_io_task;
1562 ar = (MonoAsyncResult *) data;
1564 InterlockedIncrement (&tp->busy_threads);
1565 domain = ((MonoObject *)ar)->vtable->domain;
1566 #ifndef DISABLE_SOCKETS
1567 klass = ((MonoObject *) data)->vtable->klass;
1568 is_io_task = !is_corlib_asyncresult (domain, klass);
1571 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1572 is_socket = is_socketasyncresult (domain, klass);
1574 switch (state->operation) {
1575 case AIO_OP_RECEIVE:
1576 state->total = ICALL_RECV (state);
1579 state->total = ICALL_SEND (state);
1584 /* worker threads invokes methods in different domains,
1585 * so we need to set the right domain here */
1588 if (mono_domain_is_unloading (domain) || mono_runtime_is_shutting_down ()) {
1589 threadpool_jobs_dec ((MonoObject *)ar);
1592 InterlockedDecrement (&tp->busy_threads);
1594 mono_thread_push_appdomain_ref (domain);
1595 if (threadpool_jobs_dec ((MonoObject *)ar)) {
1598 mono_thread_pop_appdomain_ref ();
1599 InterlockedDecrement (&tp->busy_threads);
1603 if (mono_domain_set (domain, FALSE)) {
1606 if (tp_item_begin_func)
1607 tp_item_begin_func (tp_item_user_data);
1609 exc = mono_async_invoke (tp, ar);
1610 if (tp_item_end_func)
1611 tp_item_end_func (tp_item_user_data);
1613 mono_internal_thread_unhandled_exception (exc);
1614 if (is_socket && tp->is_io) {
1615 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1617 if (state->completed && state->callback) {
1618 MonoAsyncResult *cb_ares;
1619 cb_ares = create_simple_asyncresult ((MonoObject *) state->callback,
1620 (MonoObject *) state);
1621 icall_append_job ((MonoObject *) cb_ares);
1624 mono_domain_set (mono_get_root_domain (), TRUE);
1626 mono_thread_pop_appdomain_ref ();
1627 InterlockedDecrement (&tp->busy_threads);
1628 clear_thread_state ();
1634 must_die = should_i_die (tp);
1636 mono_wsq_suspend (wsq);
1638 if (tp->is_io || !mono_wsq_local_pop (&data))
1639 dequeue_or_steal (tp, &data, wsq);
1643 while (!must_die && !data && n_naps < 4) {
1646 InterlockedIncrement (&tp->waiting);
1648 // Another thread may have added a job into its wsq since the last call to dequeue_or_steal
1649 // Check all the queues again before entering the wait loop
1650 dequeue_or_steal (tp, &data, wsq);
1652 InterlockedDecrement (&tp->waiting);
1656 mono_gc_set_skip_thread (TRUE);
1658 #if defined(__OpenBSD__)
1659 while (mono_cq_count (tp->queue) == 0 && (res = mono_sem_wait (&tp->new_job, TRUE)) == -1) {// && errno == EINTR) {
1661 while (mono_cq_count (tp->queue) == 0 && (res = mono_sem_timedwait (&tp->new_job, 2000, TRUE)) == -1) {// && errno == EINTR) {
1663 if (mono_runtime_is_shutting_down ())
1665 check_for_interruption_critical ();
1667 InterlockedDecrement (&tp->waiting);
1669 mono_gc_set_skip_thread (FALSE);
1671 if (mono_runtime_is_shutting_down ())
1673 must_die = should_i_die (tp);
1674 dequeue_or_steal (tp, &data, wsq);
1678 if (!data && !tp->is_io && !mono_runtime_is_shutting_down ()) {
1679 mono_wsq_local_pop (&data);
1680 if (data && must_die) {
1681 InterlockedCompareExchange (&tp->destroy_thread, 1, 0);
1682 pulse_on_new_job (tp);
1691 down = mono_runtime_is_shutting_down ();
1692 if (!down && nt <= tp->min_threads)
1694 if (down || InterlockedCompareExchange (&tp->nthreads, nt - 1, nt) == nt) {
1695 #ifndef DISABLE_PERFCOUNTERS
1696 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, -1);
1702 fire_profiler_thread_end ();
1705 tp_finish_func (tp_hooks_user_data);
1707 mono_mutex_lock (&threads_lock);
1708 g_ptr_array_remove_fast (threads, mono_thread_current ()->internal_thread);
1709 mono_mutex_unlock (&threads_lock);
1717 g_assert_not_reached ();
1721 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
1723 *workerThreads = async_tp.max_threads - async_tp.busy_threads;
1724 *completionPortThreads = async_io_tp.max_threads - async_io_tp.busy_threads;
1728 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
1730 *workerThreads = async_tp.max_threads;
1731 *completionPortThreads = async_io_tp.max_threads;
1735 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
1737 *workerThreads = async_tp.min_threads;
1738 *completionPortThreads = async_io_tp.min_threads;
1742 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
1745 gint max_io_threads;
1747 max_threads = async_tp.max_threads;
1748 if (workerThreads <= 0 || workerThreads > max_threads)
1751 max_io_threads = async_io_tp.max_threads;
1752 if (completionPortThreads <= 0 || completionPortThreads > max_io_threads)
1755 InterlockedExchange (&async_tp.min_threads, workerThreads);
1756 InterlockedExchange (&async_io_tp.min_threads, completionPortThreads);
1757 if (workerThreads > async_tp.nthreads)
1758 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_tp, TRUE, SMALL_STACK);
1759 if (completionPortThreads > async_io_tp.nthreads)
1760 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_io_tp, TRUE, SMALL_STACK);
1765 ves_icall_System_Threading_ThreadPool_SetMaxThreads (gint workerThreads, gint completionPortThreads)
1768 gint min_io_threads;
1771 cpu_count = mono_cpu_count ();
1772 min_threads = async_tp.min_threads;
1773 if (workerThreads < min_threads || workerThreads < cpu_count)
1776 /* We don't really have the concept of completion ports. Do we care here? */
1777 min_io_threads = async_io_tp.min_threads;
1778 if (completionPortThreads < min_io_threads || completionPortThreads < cpu_count)
1781 InterlockedExchange (&async_tp.max_threads, workerThreads);
1782 InterlockedExchange (&async_io_tp.max_threads, completionPortThreads);
1787 * mono_install_threadpool_thread_hooks
1788 * @start_func: the function to be called right after a new threadpool thread is created. Can be NULL.
1789 * @finish_func: the function to be called right before a thredpool thread is exiting. Can be NULL.
1790 * @user_data: argument passed to @start_func and @finish_func.
1792 * @start_fun will be called right after a threadpool thread is created and @finish_func right before a threadpool thread exits.
1793 * The calls will be made from the thread itself.
1796 mono_install_threadpool_thread_hooks (MonoThreadPoolFunc start_func, MonoThreadPoolFunc finish_func, gpointer user_data)
1798 tp_start_func = start_func;
1799 tp_finish_func = finish_func;
1800 tp_hooks_user_data = user_data;
1804 * mono_install_threadpool_item_hooks
1805 * @begin_func: the function to be called before a threadpool work item processing starts.
1806 * @end_func: the function to be called after a threadpool work item is finished.
1807 * @user_data: argument passed to @begin_func and @end_func.
1809 * The calls will be made from the thread itself and from the same AppDomain
1810 * where the work item was executed.
1814 mono_install_threadpool_item_hooks (MonoThreadPoolItemFunc begin_func, MonoThreadPoolItemFunc end_func, gpointer user_data)
1816 tp_item_begin_func = begin_func;
1817 tp_item_end_func = end_func;
1818 tp_item_user_data = user_data;
1822 mono_internal_thread_unhandled_exception (MonoObject* exc)
1824 if (mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_CURRENT) {
1828 klass = exc->vtable->klass;
1829 unloaded = is_appdomainunloaded_exception (exc->vtable->domain, klass);
1830 if (!unloaded && klass != mono_defaults.threadabortexception_class) {
1831 mono_unhandled_exception (exc);
1832 if (mono_environment_exitcode_get () == 1)
1835 if (klass == mono_defaults.threadabortexception_class)
1836 mono_thread_internal_reset_abort (mono_thread_internal_current ());
1841 * Suspend creation of new threads.
1844 mono_thread_pool_suspend (void)
1850 * Resume creation of new threads.
1853 mono_thread_pool_resume (void)