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 #endif /* !DISABLE_SOCKETS */
349 threadpool_jobs_inc (MonoObject *obj)
352 InterlockedIncrement (&obj->vtable->domain->threadpool_jobs);
356 threadpool_jobs_dec (MonoObject *obj)
364 domain = obj->vtable->domain;
365 remaining_jobs = InterlockedDecrement (&domain->threadpool_jobs);
366 if (remaining_jobs == 0 && domain->cleanup_semaphore) {
367 ReleaseSemaphore (domain->cleanup_semaphore, 1, NULL);
374 get_io_event (MonoMList **list, gint event)
384 state = mono_mlist_get_data (current);
385 if (get_event_from_state ((MonoSocketAsyncResult *) state) == event)
390 current = mono_mlist_next (current);
395 mono_mlist_set_next (prev, mono_mlist_next (current));
397 *list = mono_mlist_next (*list);
405 * select/poll wake up when a socket is closed, but epoll just removes
406 * the socket from its internal list without notification.
409 mono_thread_pool_remove_socket (int sock)
412 MonoSocketAsyncResult *state;
415 if (use_ms_threadpool ()) {
416 #ifndef DISABLE_SOCKETS
417 mono_threadpool_ms_io_remove_socket (sock);
422 if (socket_io_data.inited == 0)
425 mono_mutex_lock (&socket_io_data.io_lock);
426 if (socket_io_data.sock_to_state == NULL) {
427 mono_mutex_unlock (&socket_io_data.io_lock);
430 list = mono_g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
432 mono_g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
433 mono_mutex_unlock (&socket_io_data.io_lock);
436 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
437 if (state->operation == AIO_OP_RECEIVE)
438 state->operation = AIO_OP_RECV_JUST_CALLBACK;
439 else if (state->operation == AIO_OP_SEND)
440 state->operation = AIO_OP_SEND_JUST_CALLBACK;
442 ares = get_io_event (&list, MONO_POLLIN);
443 threadpool_append_job (&async_io_tp, ares);
445 ares = get_io_event (&list, MONO_POLLOUT);
446 threadpool_append_job (&async_io_tp, ares);
452 init_event_system (SocketIOData *data)
455 if (data->event_system == EPOLL_BACKEND) {
456 data->event_data = tp_epoll_init (data);
457 if (data->event_data == NULL) {
458 if (g_getenv ("MONO_DEBUG"))
459 g_message ("Falling back to poll()");
460 data->event_system = POLL_BACKEND;
463 #elif defined(USE_KQUEUE_FOR_THREADPOOL)
464 if (data->event_system == KQUEUE_BACKEND)
465 data->event_data = tp_kqueue_init (data);
467 if (data->event_system == POLL_BACKEND)
468 data->event_data = tp_poll_init (data);
472 socket_io_init (SocketIOData *data)
476 if (data->inited >= 2) // 2 -> initialized, 3-> cleaned up
479 inited = InterlockedCompareExchange (&data->inited, 1, 0);
482 if (data->inited >= 2)
488 mono_mutex_lock (&data->io_lock);
489 data->sock_to_state = mono_g_hash_table_new_type (g_direct_hash, g_direct_equal, MONO_HASH_VALUE_GC);
491 data->event_system = EPOLL_BACKEND;
492 #elif defined(USE_KQUEUE_FOR_THREADPOOL)
493 data->event_system = KQUEUE_BACKEND;
495 data->event_system = POLL_BACKEND;
497 if (g_getenv ("MONO_DISABLE_AIO") != NULL)
498 data->event_system = POLL_BACKEND;
500 init_event_system (data);
501 mono_thread_create_internal (mono_get_root_domain (), data->wait, data, TRUE, SMALL_STACK);
502 mono_mutex_unlock (&data->io_lock);
504 threadpool_start_thread (&async_io_tp);
508 socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
511 SocketIOData *data = &socket_io_data;
516 socket_io_init (&socket_io_data);
517 if (mono_runtime_is_shutting_down () || data->inited == 3 || data->sock_to_state == NULL)
519 if (async_tp.pool_status == 2)
522 MONO_OBJECT_SETREF (state, ares, ares);
524 fd = GPOINTER_TO_INT (state->handle);
525 mono_mutex_lock (&data->io_lock);
526 if (data->sock_to_state == NULL) {
527 mono_mutex_unlock (&data->io_lock);
530 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
532 list = mono_mlist_alloc ((MonoObject*)state);
535 list = mono_mlist_append (list, (MonoObject*)state);
539 mono_g_hash_table_replace (data->sock_to_state, state->handle, list);
540 ievt = get_events_from_list (list);
541 /* The modify function leaves the io_lock critical section. */
542 data->modify (data, fd, state->operation, ievt, is_new);
545 #ifndef DISABLE_SOCKETS
547 socket_io_filter (MonoObject *target, MonoObject *state)
550 MonoSocketAsyncResult *sock_res;
554 if (target == NULL || state == NULL)
557 domain = target->vtable->domain;
558 klass = target->vtable->klass;
559 if (socket_async_call_klass == NULL && is_socketasynccall (domain, klass))
560 socket_async_call_klass = klass;
562 if (process_async_call_klass == NULL && is_sdp_asyncreadhandler (domain, klass))
563 process_async_call_klass = klass;
565 if (klass != socket_async_call_klass && klass != process_async_call_klass)
568 sock_res = (MonoSocketAsyncResult *) state;
569 op = sock_res->operation;
570 if (op < AIO_OP_FIRST || op >= AIO_OP_LAST)
575 #endif /* !DISABLE_SOCKETS */
577 /* Returns the exception thrown when invoking, if any */
579 mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares)
581 MonoObject *exc = NULL;
583 mono_async_result_invoke (ares, &exc);
586 InterlockedDecrement (&tp->njobs);
589 InterlockedIncrement (&tp->nexecuted);
591 if (InterlockedDecrement (&monitor_njobs) == 0)
592 monitor_state = MONITOR_STATE_FALLING_ASLEEP;
598 threadpool_start_idle_threads (ThreadPool *tp)
603 stack_size = (!tp->is_io) ? 0 : SMALL_STACK;
607 if (n >= tp->min_threads)
609 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n)
612 #ifndef DISABLE_PERFCOUNTERS
613 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
615 mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE, stack_size);
621 threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer))
623 memset (tp, 0, sizeof (ThreadPool));
624 tp->min_threads = min_threads;
625 tp->max_threads = max_threads;
626 tp->async_invoke = async_invoke;
627 tp->queue = mono_cq_create ();
628 MONO_SEM_INIT (&tp->new_job, 0);
631 #ifndef DISABLE_PERFCOUNTERS
633 init_perf_counter (const char *category, const char *counter)
635 MonoString *category_str;
636 MonoString *counter_str;
642 if (category == NULL || counter == NULL)
644 root = mono_get_root_domain ();
645 category_str = mono_string_new (root, category);
646 counter_str = mono_string_new (root, counter);
647 machine = mono_string_new (root, ".");
648 return mono_perfcounter_get_impl (category_str, counter_str, NULL, machine, &type, &custom);
654 print_pool_info (ThreadPool *tp)
657 // if (tp->tail - tp->head == 0)
660 g_print ("Pool status? %d\n", InterlockedCompareExchange (&tp->pool_status, 0, 0));
661 g_print ("Min. threads: %d\n", InterlockedCompareExchange (&tp->min_threads, 0, 0));
662 g_print ("Max. threads: %d\n", InterlockedCompareExchange (&tp->max_threads, 0, 0));
663 g_print ("nthreads: %d\n", InterlockedCompareExchange (&tp->nthreads, 0, 0));
664 g_print ("busy threads: %d\n", InterlockedCompareExchange (&tp->busy_threads, 0, 0));
665 g_print ("Waiting: %d\n", InterlockedCompareExchange (&tp->waiting, 0, 0));
666 g_print ("Queued: %d\n", (tp->tail - tp->head));
667 if (tp == &async_tp) {
669 mono_mutex_lock (&wsqs_lock);
670 for (i = 0; i < wsqs->len; i++) {
671 g_print ("\tWSQ %d: %d\n", i, mono_wsq_count (g_ptr_array_index (wsqs, i)));
673 mono_mutex_unlock (&wsqs_lock);
675 g_print ("\tSockets: %d\n", mono_g_hash_table_size (socket_io_data.sock_to_state));
677 g_print ("-------------\n");
681 signal_handler (int signo)
686 g_print ("\n-----Non-IO-----\n");
687 print_pool_info (tp);
689 g_print ("\n-----IO-----\n");
690 print_pool_info (tp);
695 #define SAMPLES_PERIOD 500
696 #define HISTORY_SIZE 10
697 /* number of iteration without any jobs
698 in the queue before going to sleep */
699 #define NUM_WAITING_ITERATIONS 10
709 * - 1 if the number of threads should increase
710 * - 0 if it should not change
711 * - -1 if it should decrease
712 * - -2 in case of error
715 monitor_heuristic (gint16 *current, gint16 *history_size, SamplesHistory *history, ThreadPool *tp)
718 gint8 decision G_GNUC_UNUSED;
720 gboolean all_waitsleepjoin;
721 MonoInternalThread *thread;
724 * The following heuristic tries to approach the optimal number of threads to maximize jobs throughput. To
725 * achieve this, it simply stores the number of jobs executed (nexecuted), the number of Threads (nthreads)
726 * and the decision (nthreads_diff) for the past HISTORY_SIZE periods of time, each period being of
727 * duration SAMPLES_PERIOD ms. This history gives us an insight into what happened, and to see if we should
728 * increase or reduce the number of threads by comparing the last period (current) to the best one.
730 * The algorithm can be describe as following :
731 * - if we have a better throughput than the best period : we should either increase the number of threads
732 * in case we already have more threads, either reduce the number of threads if we have less threads; this
733 * is equivalent to move away from the number of threads of the best period, because we are currently better
734 * - if we have a worse throughput than the best period : we should either decrease the number of threads if
735 * we have more threads, either increase the number of threads if we have less threads; this is equivalent
736 * to get closer to the number of threads of the best period, because we are currently worse
739 *history_size = MIN (*history_size + 1, HISTORY_SIZE);
740 cur = *current = (*current + 1) % *history_size;
742 history [cur].nthreads = tp->nthreads;
743 history [cur].nexecuted = InterlockedExchange (&tp->nexecuted, 0);
746 /* if we have waiting thread in the pool, then do not create a new one */
747 history [cur].nthreads_diff = tp->waiting > 1 ? -1 : 0;
749 } else if (tp->nthreads < tp->min_threads) {
750 history [cur].nthreads_diff = 1;
752 } else if (*history_size <= 1) {
753 /* first iteration, let's add a thread by default */
754 history [cur].nthreads_diff = 1;
757 mono_mutex_lock (&threads_lock);
758 if (threads == NULL) {
759 mono_mutex_unlock (&threads_lock);
762 all_waitsleepjoin = TRUE;
763 for (i = 0; i < threads->len; ++i) {
764 thread = g_ptr_array_index (threads, i);
765 if (!(thread->state & ThreadState_WaitSleepJoin)) {
766 all_waitsleepjoin = FALSE;
770 mono_mutex_unlock (&threads_lock);
772 if (all_waitsleepjoin) {
773 /* we might be in a condition of starvation/deadlock with tasks waiting for each others */
774 history [cur].nthreads_diff = 1;
777 max = cur == 0 ? 1 : 0;
778 for (i = 0; i < *history_size; i++) {
781 if (history [i].nexecuted > history [max].nexecuted)
785 if (history [cur].nexecuted >= history [max].nexecuted) {
786 /* we improved the situation, let's continue ! */
787 history [cur].nthreads_diff = history [cur].nthreads >= history [max].nthreads ? 1 : -1;
790 /* we made it worse, let's return to previous situation */
791 history [cur].nthreads_diff = history [cur].nthreads >= history [max].nthreads ? -1 : 1;
798 printf ("monitor_thread: decision: %1d, history [current]: {nexecuted: %5d, nthreads: %3d, waiting: %2d, nthreads_diff: %2d}, history [max]: {nexecuted: %5d, nthreads: %3d}\n",
799 decision, history [cur].nexecuted, history [cur].nthreads, tp->waiting, history [cur].nthreads_diff, history [max].nexecuted, history [max].nthreads);
802 return history [cur].nthreads_diff;
806 monitor_thread (gpointer unused)
808 ThreadPool *pools [2];
809 MonoInternalThread *thread;
813 gint8 num_waiting_iterations = 0;
815 gint16 history_size = 0, current = -1;
816 SamplesHistory *history = malloc (sizeof (SamplesHistory) * HISTORY_SIZE);
818 pools [0] = &async_tp;
819 pools [1] = &async_io_tp;
820 thread = mono_thread_internal_current ();
821 ves_icall_System_Threading_Thread_SetName_internal (thread, mono_string_new (mono_domain_get (), "Threadpool monitor"));
824 i = 10; //number of spurious awakes we tolerate before doing a round of rebalancing.
825 mono_gc_set_skip_thread (TRUE);
826 MONO_PREPARE_BLOCKING
829 ts = mono_msec_ticks ();
830 if (SleepEx (ms, TRUE) == 0)
832 ms -= (mono_msec_ticks () - ts);
833 if (mono_runtime_is_shutting_down ())
835 check_for_interruption_critical ();
836 } while (ms > 0 && i--);
838 mono_gc_set_skip_thread (FALSE);
840 if (mono_runtime_is_shutting_down ())
846 /* threadpool is cleaning up */
847 if (async_tp.pool_status == 2 || async_io_tp.pool_status == 2)
850 MONO_PREPARE_BLOCKING
851 switch (monitor_state) {
852 case MONITOR_STATE_AWAKE:
853 num_waiting_iterations = 0;
855 case MONITOR_STATE_FALLING_ASLEEP:
856 if (++num_waiting_iterations == NUM_WAITING_ITERATIONS) {
857 if (monitor_state == MONITOR_STATE_FALLING_ASLEEP && InterlockedCompareExchange (&monitor_state, MONITOR_STATE_SLEEPING, MONITOR_STATE_FALLING_ASLEEP) == MONITOR_STATE_FALLING_ASLEEP) {
858 MONO_SEM_WAIT (&monitor_sem);
860 num_waiting_iterations = 0;
866 case MONITOR_STATE_SLEEPING:
867 g_assert_not_reached ();
871 for (i = 0; i < 2; i++) {
876 if (!tp->waiting && mono_cq_count (tp->queue) > 0)
877 threadpool_start_thread (tp);
879 gint8 nthreads_diff = monitor_heuristic (¤t, &history_size, history, tp);
881 if (nthreads_diff == 1)
882 threadpool_start_thread (tp);
883 else if (nthreads_diff == -1)
884 threadpool_kill_thread (tp);
891 mono_thread_pool_init_tls (void)
893 if (use_ms_threadpool ()) {
894 mono_threadpool_ms_init_tls ();
902 mono_thread_pool_init (void)
904 gint threads_per_cpu = 1;
909 if (use_ms_threadpool ()) {
910 mono_threadpool_ms_init ();
914 cpu_count = mono_cpu_count ();
919 result = InterlockedCompareExchange (&tp_inited, 1, 0);
928 MONO_GC_REGISTER_ROOT_FIXED (socket_io_data.sock_to_state);
929 mono_mutex_init_recursive (&socket_io_data.io_lock);
930 if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
931 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
932 if (threads_per_cpu < 1)
936 thread_count = MIN (cpu_count * threads_per_cpu, 100 * cpu_count);
937 threadpool_init (&async_tp, thread_count, MAX (100 * cpu_count, thread_count), async_invoke_thread);
938 threadpool_init (&async_io_tp, cpu_count * 2, cpu_count * 4, async_invoke_thread);
939 async_io_tp.is_io = TRUE;
941 async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
942 g_assert (async_call_klass);
944 mono_mutex_init (&threads_lock);
945 threads = g_ptr_array_sized_new (thread_count);
948 mono_mutex_init_recursive (&wsqs_lock);
949 wsqs = g_ptr_array_sized_new (MAX (100 * cpu_count, thread_count));
951 #ifndef DISABLE_PERFCOUNTERS
952 async_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "Work Items Added");
953 g_assert (async_tp.pc_nitems);
955 async_io_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "IO Work Items Added");
956 g_assert (async_io_tp.pc_nitems);
958 async_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of Threads");
959 g_assert (async_tp.pc_nthreads);
961 async_io_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of IO Threads");
962 g_assert (async_io_tp.pc_nthreads);
966 signal (SIGALRM, signal_handler);
970 MONO_SEM_INIT (&monitor_sem, 0);
971 monitor_state = MONITOR_STATE_AWAKE;
975 static MonoAsyncResult *
976 create_simple_asyncresult (MonoObject *target, MonoObject *state)
978 MonoDomain *domain = mono_domain_get ();
979 MonoAsyncResult *ares;
981 /* Don't call mono_async_result_new() to avoid capturing the context */
982 ares = (MonoAsyncResult *) mono_object_new (domain, mono_defaults.asyncresult_class);
983 MONO_OBJECT_SETREF (ares, async_delegate, target);
984 MONO_OBJECT_SETREF (ares, async_state, state);
989 icall_append_io_job (MonoObject *target, MonoSocketAsyncResult *state)
991 MonoAsyncResult *ares;
993 ares = create_simple_asyncresult (target, (MonoObject *) state);
995 if (use_ms_threadpool ()) {
996 #ifndef DISABLE_SOCKETS
997 mono_threadpool_ms_io_add (ares, state);
1002 socket_io_add (ares, state);
1006 mono_thread_pool_begin_invoke (MonoDomain *domain, MonoObject *target, MonoMethod *method, gpointer *params)
1008 MonoMethodMessage *message;
1009 MonoAsyncResult *async_result;
1010 MonoAsyncCall *async_call;
1011 MonoDelegate *async_callback = NULL;
1012 MonoObject *state = NULL;
1014 if (use_ms_threadpool ())
1015 return mono_threadpool_ms_begin_invoke (domain, target, method, params);
1017 message = mono_method_call_message_new (method, params, mono_get_delegate_invoke (method->klass), (params != NULL) ? (&async_callback) : NULL, (params != NULL) ? (&state) : NULL);
1019 async_call = (MonoAsyncCall*)mono_object_new (domain, async_call_klass);
1020 MONO_OBJECT_SETREF (async_call, msg, message);
1021 MONO_OBJECT_SETREF (async_call, state, state);
1023 if (async_callback) {
1024 async_call->cb_method = mono_get_delegate_invoke (((MonoObject*) async_callback)->vtable->klass);
1025 MONO_OBJECT_SETREF (async_call, cb_target, async_callback);
1028 async_result = mono_async_result_new (domain, NULL, async_call->state, NULL, (MonoObject*) async_call);
1029 MONO_OBJECT_SETREF (async_result, async_delegate, target);
1031 #ifndef DISABLE_SOCKETS
1032 if (socket_io_filter (target, state)) {
1033 socket_io_add (async_result, (MonoSocketAsyncResult *) state);
1034 return async_result;
1037 threadpool_append_job (&async_tp, (MonoObject *) async_result);
1038 return async_result;
1042 mono_thread_pool_end_invoke (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1047 if (use_ms_threadpool ()) {
1048 return mono_threadpool_ms_end_invoke (ares, out_args, exc);
1054 /* check if already finished */
1055 mono_monitor_enter ((MonoObject *) ares);
1057 if (ares->endinvoke_called) {
1058 *exc = (MonoObject *) mono_get_exception_invalid_operation (NULL);
1059 mono_monitor_exit ((MonoObject *) ares);
1063 ares->endinvoke_called = 1;
1064 /* wait until we are really finished */
1065 if (!ares->completed) {
1066 if (ares->handle == NULL) {
1067 wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1068 g_assert(wait_event != 0);
1069 MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), wait_event));
1071 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
1073 mono_monitor_exit ((MonoObject *) ares);
1074 MONO_PREPARE_BLOCKING
1075 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
1076 MONO_FINISH_BLOCKING
1078 mono_monitor_exit ((MonoObject *) ares);
1081 ac = (MonoAsyncCall *) ares->object_data;
1082 g_assert (ac != NULL);
1083 *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1084 *out_args = ac->out_args;
1090 threadpool_kill_idle_threads (ThreadPool *tp)
1094 n = (gint) InterlockedCompareExchange (&tp->max_threads, 0, -1);
1097 MONO_SEM_POST (&tp->new_job);
1102 mono_thread_pool_cleanup (void)
1104 if (use_ms_threadpool ()) {
1105 mono_threadpool_ms_cleanup ();
1109 if (InterlockedExchange (&async_io_tp.pool_status, 2) == 1) {
1110 socket_io_cleanup (&socket_io_data); /* Empty when DISABLE_SOCKETS is defined */
1111 threadpool_kill_idle_threads (&async_io_tp);
1114 if (async_io_tp.queue != NULL) {
1115 MONO_SEM_DESTROY (&async_io_tp.new_job);
1116 threadpool_free_queue (&async_io_tp);
1120 if (InterlockedExchange (&async_tp.pool_status, 2) == 1) {
1121 threadpool_kill_idle_threads (&async_tp);
1122 threadpool_free_queue (&async_tp);
1126 mono_mutex_lock (&threads_lock);
1128 g_ptr_array_free (threads, FALSE);
1130 mono_mutex_unlock (&threads_lock);
1134 mono_mutex_lock (&wsqs_lock);
1135 mono_wsq_cleanup ();
1137 g_ptr_array_free (wsqs, TRUE);
1139 mono_mutex_unlock (&wsqs_lock);
1140 MONO_SEM_DESTROY (&async_tp.new_job);
1143 MONO_SEM_DESTROY (&monitor_sem);
1147 threadpool_start_thread (ThreadPool *tp)
1151 MonoInternalThread *thread;
1153 stack_size = (!tp->is_io) ? 0 : SMALL_STACK;
1154 while (!mono_runtime_is_shutting_down () && (n = tp->nthreads) < tp->max_threads) {
1155 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n) {
1156 #ifndef DISABLE_PERFCOUNTERS
1157 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
1160 thread = mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE, stack_size);
1162 mono_mutex_lock (&threads_lock);
1163 thread = mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE, stack_size);
1164 g_assert (threads != NULL);
1165 g_ptr_array_add (threads, thread);
1166 mono_mutex_unlock (&threads_lock);
1176 pulse_on_new_job (ThreadPool *tp)
1179 MONO_SEM_POST (&tp->new_job);
1183 threadpool_kill_thread (ThreadPool *tp)
1185 if (tp->destroy_thread == 0 && InterlockedCompareExchange (&tp->destroy_thread, 1, 0) == 0)
1186 pulse_on_new_job (tp);
1190 icall_append_job (MonoObject *ar)
1192 threadpool_append_jobs (&async_tp, &ar, 1);
1196 threadpool_append_job (ThreadPool *tp, MonoObject *ar)
1198 threadpool_append_jobs (tp, &ar, 1);
1202 threadpool_append_async_io_jobs (MonoObject **jobs, gint njobs)
1204 threadpool_append_jobs (&async_io_tp, jobs, njobs);
1208 threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs)
1213 if (mono_runtime_is_shutting_down ())
1216 if (tp->pool_status == 0 && InterlockedCompareExchange (&tp->pool_status, 1, 0) == 0) {
1218 monitor_internal_thread = mono_thread_create_internal (mono_get_root_domain (), monitor_thread, NULL, TRUE, SMALL_STACK);
1219 monitor_internal_thread->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
1220 threadpool_start_thread (tp);
1222 /* Create on demand up to min_threads to avoid startup penalty for apps that don't use
1223 * the threadpool that much
1225 if (mono_config_is_server_mode ()) {
1226 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, tp, TRUE, SMALL_STACK);
1230 InterlockedAdd (&monitor_njobs, njobs);
1232 if (monitor_state == MONITOR_STATE_SLEEPING && InterlockedCompareExchange (&monitor_state, MONITOR_STATE_AWAKE, MONITOR_STATE_SLEEPING) == MONITOR_STATE_SLEEPING)
1233 MONO_SEM_POST (&monitor_sem);
1235 if (monitor_state == MONITOR_STATE_FALLING_ASLEEP)
1236 InterlockedCompareExchange (&monitor_state, MONITOR_STATE_AWAKE, MONITOR_STATE_FALLING_ASLEEP);
1238 for (i = 0; i < njobs; i++) {
1240 if (ar == NULL || mono_domain_is_unloading (ar->vtable->domain))
1241 continue; /* Might happen when cleaning domain jobs */
1242 threadpool_jobs_inc (ar);
1243 #ifndef DISABLE_PERFCOUNTERS
1244 mono_perfcounter_update_value (tp->pc_nitems, TRUE, 1);
1246 if (!tp->is_io && mono_wsq_local_push (ar))
1249 mono_cq_enqueue (tp->queue, ar);
1253 InterlockedAdd (&tp->njobs, njobs);
1256 for (i = 0; tp->waiting > 0 && i < MIN(njobs, tp->max_threads); i++)
1257 pulse_on_new_job (tp);
1261 threadpool_clear_queue (ThreadPool *tp, MonoDomain *domain)
1264 MonoMList *other = NULL;
1265 MonoCQ *queue = tp->queue;
1270 while (mono_cq_dequeue (queue, &obj)) {
1273 if (obj->vtable->domain != domain)
1274 other = mono_mlist_prepend (other, obj);
1275 threadpool_jobs_dec (obj);
1278 if (mono_runtime_is_shutting_down ())
1282 threadpool_append_job (tp, (MonoObject *) mono_mlist_get_data (other));
1283 other = mono_mlist_next (other);
1288 remove_sockstate_for_domain (gpointer key, gpointer value, gpointer user_data)
1290 MonoMList *list = value;
1291 gboolean remove = FALSE;
1293 MonoObject *data = mono_mlist_get_data (list);
1294 if (mono_object_domain (data) == user_data) {
1296 mono_mlist_set_data (list, NULL);
1298 list = mono_mlist_next (list);
1300 //FIXME is there some sort of additional unregistration we need to perform here?
1305 * Clean up the threadpool of all domain jobs.
1306 * Can only be called as part of the domain unloading process as
1307 * it will wait for all jobs to be visible to the interruption code.
1310 mono_thread_pool_remove_domain_jobs (MonoDomain *domain, int timeout)
1316 if (use_ms_threadpool ()) {
1317 return mono_threadpool_ms_remove_domain_jobs (domain, timeout);
1323 g_assert (domain->state == MONO_APPDOMAIN_UNLOADING);
1325 threadpool_clear_queue (&async_tp, domain);
1326 threadpool_clear_queue (&async_io_tp, domain);
1328 mono_mutex_lock (&socket_io_data.io_lock);
1329 if (socket_io_data.sock_to_state)
1330 mono_g_hash_table_foreach_remove (socket_io_data.sock_to_state, remove_sockstate_for_domain, domain);
1332 mono_mutex_unlock (&socket_io_data.io_lock);
1335 * There might be some threads out that could be about to execute stuff from the given domain.
1336 * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
1338 sem_handle = CreateSemaphore (NULL, 0, 1, NULL);
1340 domain->cleanup_semaphore = sem_handle;
1342 * The memory barrier here is required to have global ordering between assigning to cleanup_semaphone
1343 * and reading threadpool_jobs.
1344 * Otherwise this thread could read a stale version of threadpool_jobs and wait forever.
1346 mono_memory_write_barrier ();
1348 if (domain->threadpool_jobs && timeout != -1)
1349 start_time = mono_msec_ticks ();
1350 while (domain->threadpool_jobs) {
1351 MONO_PREPARE_BLOCKING
1352 WaitForSingleObject (sem_handle, timeout);
1353 MONO_FINISH_BLOCKING
1354 if (timeout != -1 && (mono_msec_ticks () - start_time) > timeout) {
1360 domain->cleanup_semaphore = NULL;
1361 CloseHandle (sem_handle);
1366 threadpool_free_queue (ThreadPool *tp)
1368 mono_cq_destroy (tp->queue);
1373 mono_thread_pool_is_queue_array (MonoArray *o)
1375 if (use_ms_threadpool ()) {
1376 return mono_threadpool_ms_is_queue_array (o);
1379 // gpointer obj = o;
1381 // FIXME: need some fix in sgen code.
1391 mono_mutex_lock (&wsqs_lock);
1392 wsq = mono_wsq_create ();
1394 mono_mutex_unlock (&wsqs_lock);
1397 for (i = 0; i < wsqs->len; i++) {
1398 if (g_ptr_array_index (wsqs, i) == NULL) {
1399 wsqs->pdata [i] = wsq;
1400 mono_mutex_unlock (&wsqs_lock);
1404 g_ptr_array_add (wsqs, wsq);
1405 mono_mutex_unlock (&wsqs_lock);
1410 remove_wsq (MonoWSQ *wsq)
1417 mono_mutex_lock (&wsqs_lock);
1419 mono_mutex_unlock (&wsqs_lock);
1422 g_ptr_array_remove_fast (wsqs, wsq);
1425 * Only clean this up when shutting down, any other case will error out
1426 * if we're removing a queue that still has work items.
1428 if (mono_runtime_is_shutting_down ()) {
1429 while (mono_wsq_local_pop (&data)) {
1430 threadpool_jobs_dec (data);
1434 mono_wsq_destroy (wsq);
1435 mono_mutex_unlock (&wsqs_lock);
1439 try_steal (MonoWSQ *local_wsq, gpointer *data, gboolean retry)
1444 if (wsqs == NULL || data == NULL || *data != NULL)
1449 if (mono_runtime_is_shutting_down ())
1452 MONO_PREPARE_BLOCKING
1453 mono_mutex_lock (&wsqs_lock);
1454 MONO_FINISH_BLOCKING
1455 for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
1458 wsq = wsqs->pdata [i];
1459 if (wsq == local_wsq || mono_wsq_count (wsq) == 0)
1461 mono_wsq_try_steal (wsqs->pdata [i], data, ms);
1462 if (*data != NULL) {
1463 mono_mutex_unlock (&wsqs_lock);
1467 mono_mutex_unlock (&wsqs_lock);
1469 } while (retry && ms < 11);
1473 dequeue_or_steal (ThreadPool *tp, gpointer *data, MonoWSQ *local_wsq)
1475 MonoCQ *queue = tp->queue;
1476 if (mono_runtime_is_shutting_down () || !queue)
1478 mono_cq_dequeue (queue, (MonoObject **) data);
1479 if (!tp->is_io && !*data)
1480 try_steal (local_wsq, data, FALSE);
1481 return (*data != NULL);
1485 should_i_die (ThreadPool *tp)
1487 gboolean result = FALSE;
1488 if (tp->destroy_thread == 1 && InterlockedCompareExchange (&tp->destroy_thread, 0, 1) == 1)
1489 result = (tp->nthreads > tp->min_threads);
1494 set_tp_thread_info (ThreadPool *tp)
1497 MonoInternalThread *thread = mono_thread_internal_current ();
1499 mono_profiler_thread_start (thread->tid);
1500 name = (tp->is_io) ? "IO Threadpool worker" : "Threadpool worker";
1501 mono_thread_set_name_internal (thread, mono_string_new (mono_domain_get (), name), FALSE);
1505 clear_thread_state (void)
1507 MonoInternalThread *thread = mono_thread_internal_current ();
1508 /* If the callee changes the background status, set it back to TRUE */
1509 mono_thread_clr_state (thread , ~ThreadState_Background);
1510 if (!mono_thread_test_state (thread , ThreadState_Background))
1511 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
1515 check_for_interruption_critical (void)
1517 MonoInternalThread *thread;
1518 /*RULE NUMBER ONE OF SKIP_THREAD: NEVER POKE MANAGED STATE.*/
1519 mono_gc_set_skip_thread (FALSE);
1521 thread = mono_thread_internal_current ();
1522 if (THREAD_WANTS_A_BREAK (thread))
1523 mono_thread_interruption_checkpoint ();
1525 /*RULE NUMBER TWO OF SKIP_THREAD: READ RULE NUMBER ONE.*/
1526 mono_gc_set_skip_thread (TRUE);
1530 fire_profiler_thread_end (void)
1532 MonoInternalThread *thread = mono_thread_internal_current ();
1533 mono_profiler_thread_end (thread->tid);
1537 async_invoke_thread (gpointer data)
1549 set_tp_thread_info (tp);
1552 tp_start_func (tp_hooks_user_data);
1556 MonoAsyncResult *ar;
1558 gboolean is_io_task;
1563 ar = (MonoAsyncResult *) data;
1565 InterlockedIncrement (&tp->busy_threads);
1566 domain = ((MonoObject *)ar)->vtable->domain;
1567 #ifndef DISABLE_SOCKETS
1568 klass = ((MonoObject *) data)->vtable->klass;
1569 is_io_task = !is_corlib_asyncresult (domain, klass);
1572 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1573 is_socket = is_socketasyncresult (domain, klass);
1577 /* worker threads invokes methods in different domains,
1578 * so we need to set the right domain here */
1581 if (mono_domain_is_unloading (domain) || mono_runtime_is_shutting_down ()) {
1582 threadpool_jobs_dec ((MonoObject *)ar);
1585 InterlockedDecrement (&tp->busy_threads);
1587 mono_thread_push_appdomain_ref (domain);
1588 if (threadpool_jobs_dec ((MonoObject *)ar)) {
1591 mono_thread_pop_appdomain_ref ();
1592 InterlockedDecrement (&tp->busy_threads);
1596 if (mono_domain_set (domain, FALSE)) {
1599 if (tp_item_begin_func)
1600 tp_item_begin_func (tp_item_user_data);
1602 exc = mono_async_invoke (tp, ar);
1603 if (tp_item_end_func)
1604 tp_item_end_func (tp_item_user_data);
1606 mono_internal_thread_unhandled_exception (exc);
1607 if (is_socket && tp->is_io) {
1608 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1610 if (state->completed && state->callback) {
1611 MonoAsyncResult *cb_ares;
1612 cb_ares = create_simple_asyncresult ((MonoObject *) state->callback,
1613 (MonoObject *) state);
1614 icall_append_job ((MonoObject *) cb_ares);
1617 mono_domain_set (mono_get_root_domain (), TRUE);
1619 mono_thread_pop_appdomain_ref ();
1620 InterlockedDecrement (&tp->busy_threads);
1621 clear_thread_state ();
1627 must_die = should_i_die (tp);
1629 mono_wsq_suspend (wsq);
1631 if (tp->is_io || !mono_wsq_local_pop (&data))
1632 dequeue_or_steal (tp, &data, wsq);
1636 while (!must_die && !data && n_naps < 4) {
1639 InterlockedIncrement (&tp->waiting);
1641 // Another thread may have added a job into its wsq since the last call to dequeue_or_steal
1642 // Check all the queues again before entering the wait loop
1643 dequeue_or_steal (tp, &data, wsq);
1645 InterlockedDecrement (&tp->waiting);
1649 mono_gc_set_skip_thread (TRUE);
1650 MONO_PREPARE_BLOCKING
1652 #if defined(__OpenBSD__)
1653 while (mono_cq_count (tp->queue) == 0 && (res = mono_sem_wait (&tp->new_job, TRUE)) == -1) {// && errno == EINTR) {
1655 while (mono_cq_count (tp->queue) == 0 && (res = mono_sem_timedwait (&tp->new_job, 2000, TRUE)) == -1) {// && errno == EINTR) {
1657 if (mono_runtime_is_shutting_down ())
1659 check_for_interruption_critical ();
1661 InterlockedDecrement (&tp->waiting);
1663 MONO_FINISH_BLOCKING
1664 mono_gc_set_skip_thread (FALSE);
1666 if (mono_runtime_is_shutting_down ())
1668 must_die = should_i_die (tp);
1669 dequeue_or_steal (tp, &data, wsq);
1673 if (!data && !tp->is_io && !mono_runtime_is_shutting_down ()) {
1674 mono_wsq_local_pop (&data);
1675 if (data && must_die) {
1676 InterlockedCompareExchange (&tp->destroy_thread, 1, 0);
1677 pulse_on_new_job (tp);
1686 down = mono_runtime_is_shutting_down ();
1687 if (!down && nt <= tp->min_threads)
1689 if (down || InterlockedCompareExchange (&tp->nthreads, nt - 1, nt) == nt) {
1690 #ifndef DISABLE_PERFCOUNTERS
1691 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, -1);
1697 fire_profiler_thread_end ();
1700 tp_finish_func (tp_hooks_user_data);
1704 mono_mutex_lock (&threads_lock);
1706 g_ptr_array_remove_fast (threads, mono_thread_current ()->internal_thread);
1707 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)
1846 if (use_ms_threadpool ()) {
1847 mono_threadpool_ms_suspend ();
1854 * Resume creation of new threads.
1857 mono_thread_pool_resume (void)
1859 if (use_ms_threadpool ()) {
1860 mono_threadpool_ms_resume ();