2 * threadpool.c: global thread pool
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Gonzalo Paniagua Javier (gonzalo@ximian.com)
8 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
9 * Copyright 2004-2010 Novell, Inc (http://www.novell.com)
10 * Copyright 2001 Xamarin Inc (http://www.xamarin.com)
16 #include <mono/metadata/profiler-private.h>
17 #include <mono/metadata/threads.h>
18 #include <mono/metadata/threads-types.h>
19 #include <mono/metadata/threadpool-internals.h>
20 #include <mono/metadata/exception.h>
21 #include <mono/metadata/environment.h>
22 #include <mono/metadata/mono-config.h>
23 #include <mono/metadata/mono-mlist.h>
24 #include <mono/metadata/mono-perfcounters.h>
25 #include <mono/metadata/socket-io.h>
26 #include <mono/metadata/mono-cq.h>
27 #include <mono/metadata/mono-wsq.h>
28 #include <mono/metadata/mono-ptr-array.h>
29 #include <mono/metadata/object-internals.h>
30 #include <mono/io-layer/io-layer.h>
31 #include <mono/utils/mono-time.h>
32 #include <mono/utils/mono-proclib.h>
33 #include <mono/utils/mono-semaphore.h>
34 #include <mono/utils/atomic.h>
36 #ifdef HAVE_SYS_TIME_H
39 #include <sys/types.h>
46 #ifdef HAVE_SYS_SOCKET_H
47 #include <sys/socket.h>
49 #include <mono/utils/mono-poll.h>
51 #include <sys/epoll.h>
54 #include <sys/event.h>
58 #ifndef DISABLE_SOCKETS
59 #include "mono/io-layer/socket-wrappers.h"
62 #include "threadpool.h"
63 #include "threadpool-ms.h"
64 #include "threadpool-ms-io.h"
67 use_ms_threadpool (void)
69 static gboolean use_ms_tp = -1;
70 const gchar *mono_threadpool_env;
73 else if (!(mono_threadpool_env = g_getenv ("MONO_THREADPOOL")))
74 return use_ms_tp = FALSE;
75 else if (strcmp (mono_threadpool_env, "microsoft") == 0)
76 return use_ms_tp = TRUE;
78 return use_ms_tp = FALSE;
81 #define THREAD_WANTS_A_BREAK(t) ((t->state & (ThreadState_StopRequested | \
82 ThreadState_SuspendRequested)) != 0)
84 /* DEBUG: prints tp data every 2s */
87 /* mono_thread_pool_init called */
88 static volatile int tp_inited;
98 MONITOR_STATE_FALLING_ASLEEP,
99 MONITOR_STATE_SLEEPING
102 static SocketIOData socket_io_data;
106 MonoCQ *queue; /* GC root */
108 volatile gint waiting; /* threads waiting for a work item */
111 volatile gint pool_status; /* 0 -> not initialized, 1 -> initialized, 2 -> cleaning up */
112 /* min, max, n and busy -> Interlocked */
113 volatile gint min_threads;
114 volatile gint max_threads;
115 volatile gint nthreads;
116 volatile gint busy_threads;
118 void (*async_invoke) (gpointer data);
119 void *pc_nitems; /* Performance counter for total number of items in added */
120 void *pc_nthreads; /* Performance counter for total number of active threads */
122 volatile gint destroy_thread;
124 volatile gint32 njobs;
126 volatile gint32 nexecuted;
130 static ThreadPool async_tp;
131 static ThreadPool async_io_tp;
133 static void async_invoke_thread (gpointer data);
134 static MonoObject *mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares);
135 static void threadpool_free_queue (ThreadPool *tp);
136 static void threadpool_append_job (ThreadPool *tp, MonoObject *ar);
137 static void threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs);
138 static void threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer));
139 static void threadpool_start_idle_threads (ThreadPool *tp);
140 static void threadpool_kill_idle_threads (ThreadPool *tp);
141 static gboolean threadpool_start_thread (ThreadPool *tp);
142 static void threadpool_kill_thread (ThreadPool *tp);
143 static void monitor_thread (gpointer data);
144 static int get_event_from_state (MonoSocketAsyncResult *state);
146 static MonoClass *async_call_klass;
147 static MonoClass *socket_async_call_klass;
148 static MonoClass *process_async_call_klass;
150 static GPtrArray *threads;
151 mono_mutex_t threads_lock;
152 static GPtrArray *wsqs;
153 mono_mutex_t wsqs_lock;
154 static gboolean suspended;
156 static volatile gint32 monitor_njobs = 0;
157 static volatile gint32 monitor_state;
158 static MonoSemType monitor_sem;
159 static MonoInternalThread *monitor_internal_thread;
162 static MonoThreadPoolFunc tp_start_func;
163 static MonoThreadPoolFunc tp_finish_func;
164 static gpointer tp_hooks_user_data;
165 static MonoThreadPoolItemFunc tp_item_begin_func;
166 static MonoThreadPoolItemFunc tp_item_end_func;
167 static gpointer tp_item_user_data;
177 AIO_OP_RECV_JUST_CALLBACK,
178 AIO_OP_SEND_JUST_CALLBACK,
182 AIO_OP_ACCEPTRECEIVE,
183 AIO_OP_RECEIVE_BUFFERS,
188 // #include <mono/metadata/tpool-poll.c>
189 gpointer tp_poll_init (SocketIOData *data);
192 #include <mono/metadata/tpool-epoll.c>
193 #elif defined(USE_KQUEUE_FOR_THREADPOOL)
194 #include <mono/metadata/tpool-kqueue.c>
197 * Functions to check whenever a class is given system class. We need to cache things in MonoDomain since some of the
198 * assemblies can be unloaded.
202 is_system_type (MonoDomain *domain, MonoClass *klass)
204 if (domain->system_image == NULL)
205 domain->system_image = mono_image_loaded ("System");
207 return klass->image == domain->system_image;
211 is_corlib_type (MonoDomain *domain, MonoClass *klass)
213 return klass->image == mono_defaults.corlib;
216 #define check_type_cached(domain, ASSEMBLY, _class, _namespace, _name, loc) do { \
218 return *loc == _class; \
219 if (is_##ASSEMBLY##_type (domain, _class) && !strcmp (_name, _class->name) && !strcmp (_namespace, _class->name_space)) { \
226 #define check_corlib_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, corlib, _class, _namespace, _name, loc)
228 #define check_system_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, system, _class, _namespace, _name, loc)
231 is_corlib_asyncresult (MonoDomain *domain, MonoClass *klass)
233 check_corlib_type_cached (domain, klass, "System.Runtime.Remoting.Messaging", "AsyncResult", &domain->corlib_asyncresult_class);
237 is_socketasyncresult (MonoDomain *domain, MonoClass *klass)
239 static MonoClass *socket_async_result_klass = NULL;
240 check_system_type_cached (domain, klass, "System.Net.Sockets", "SocketAsyncResult", &socket_async_result_klass);
244 is_socketasynccall (MonoDomain *domain, MonoClass *klass)
246 static MonoClass *socket_async_callback_klass = NULL;
247 check_system_type_cached (domain, klass, "System.Net.Sockets", "SocketAsyncCallback", &socket_async_callback_klass);
251 is_appdomainunloaded_exception (MonoDomain *domain, MonoClass *klass)
253 check_corlib_type_cached (domain, klass, "System", "AppDomainUnloadedException", &domain->ad_unloaded_ex_class);
257 is_sd_process (MonoDomain *domain, MonoClass *klass)
259 check_system_type_cached (domain, klass, "System.Diagnostics", "Process", &domain->process_class);
263 is_sdp_asyncreadhandler (MonoDomain *domain, MonoClass *klass)
266 return (klass->nested_in &&
267 is_sd_process (domain, klass->nested_in) &&
268 !strcmp (klass->name, "AsyncReadHandler"));
272 #ifdef DISABLE_SOCKETS
275 socket_io_cleanup (SocketIOData *data)
280 get_event_from_state (MonoSocketAsyncResult *state)
282 g_assert_not_reached ();
287 get_events_from_list (MonoMList *list)
295 socket_io_cleanup (SocketIOData *data)
297 mono_mutex_lock (&data->io_lock);
298 if (data->inited != 2) {
299 mono_mutex_unlock (&data->io_lock);
303 data->shutdown (data->event_data);
304 mono_mutex_unlock (&data->io_lock);
308 get_event_from_state (MonoSocketAsyncResult *state)
310 switch (state->operation) {
313 case AIO_OP_RECV_JUST_CALLBACK:
314 case AIO_OP_RECEIVEFROM:
315 case AIO_OP_READPIPE:
316 case AIO_OP_ACCEPTRECEIVE:
317 case AIO_OP_RECEIVE_BUFFERS:
320 case AIO_OP_SEND_JUST_CALLBACK:
323 case AIO_OP_SEND_BUFFERS:
324 case AIO_OP_DISCONNECT:
326 default: /* Should never happen */
327 g_message ("get_event_from_state: unknown value in switch!!!");
333 get_events_from_list (MonoMList *list)
335 MonoSocketAsyncResult *state;
338 while (list && (state = (MonoSocketAsyncResult *)mono_mlist_get_data (list))) {
339 events |= get_event_from_state (state);
340 list = mono_mlist_next (list);
346 #define ICALL_RECV(x) ves_icall_System_Net_Sockets_Socket_Receive_internal (\
347 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
348 x->socket_flags, &x->error);
350 #define ICALL_SEND(x) ves_icall_System_Net_Sockets_Socket_Send_internal (\
351 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
352 x->socket_flags, &x->error);
354 #endif /* !DISABLE_SOCKETS */
357 threadpool_jobs_inc (MonoObject *obj)
360 InterlockedIncrement (&obj->vtable->domain->threadpool_jobs);
364 threadpool_jobs_dec (MonoObject *obj)
372 domain = obj->vtable->domain;
373 remaining_jobs = InterlockedDecrement (&domain->threadpool_jobs);
374 if (remaining_jobs == 0 && domain->cleanup_semaphore) {
375 ReleaseSemaphore (domain->cleanup_semaphore, 1, NULL);
382 get_io_event (MonoMList **list, gint event)
392 state = mono_mlist_get_data (current);
393 if (get_event_from_state ((MonoSocketAsyncResult *) state) == event)
398 current = mono_mlist_next (current);
403 mono_mlist_set_next (prev, mono_mlist_next (current));
405 *list = mono_mlist_next (*list);
413 * select/poll wake up when a socket is closed, but epoll just removes
414 * the socket from its internal list without notification.
417 mono_thread_pool_remove_socket (int sock)
420 MonoSocketAsyncResult *state;
423 if (use_ms_threadpool ()) {
424 #ifndef DISABLE_SOCKETS
425 mono_threadpool_ms_io_remove_socket (sock);
430 if (socket_io_data.inited == 0)
433 mono_mutex_lock (&socket_io_data.io_lock);
434 if (socket_io_data.sock_to_state == NULL) {
435 mono_mutex_unlock (&socket_io_data.io_lock);
438 list = mono_g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
440 mono_g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
441 mono_mutex_unlock (&socket_io_data.io_lock);
444 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
445 if (state->operation == AIO_OP_RECEIVE)
446 state->operation = AIO_OP_RECV_JUST_CALLBACK;
447 else if (state->operation == AIO_OP_SEND)
448 state->operation = AIO_OP_SEND_JUST_CALLBACK;
450 ares = get_io_event (&list, MONO_POLLIN);
451 threadpool_append_job (&async_io_tp, ares);
453 ares = get_io_event (&list, MONO_POLLOUT);
454 threadpool_append_job (&async_io_tp, ares);
460 init_event_system (SocketIOData *data)
463 if (data->event_system == EPOLL_BACKEND) {
464 data->event_data = tp_epoll_init (data);
465 if (data->event_data == NULL) {
466 if (g_getenv ("MONO_DEBUG"))
467 g_message ("Falling back to poll()");
468 data->event_system = POLL_BACKEND;
471 #elif defined(USE_KQUEUE_FOR_THREADPOOL)
472 if (data->event_system == KQUEUE_BACKEND)
473 data->event_data = tp_kqueue_init (data);
475 if (data->event_system == POLL_BACKEND)
476 data->event_data = tp_poll_init (data);
480 socket_io_init (SocketIOData *data)
484 if (data->inited >= 2) // 2 -> initialized, 3-> cleaned up
487 inited = InterlockedCompareExchange (&data->inited, 1, 0);
490 if (data->inited >= 2)
496 mono_mutex_lock (&data->io_lock);
497 data->sock_to_state = mono_g_hash_table_new_type (g_direct_hash, g_direct_equal, MONO_HASH_VALUE_GC);
499 data->event_system = EPOLL_BACKEND;
500 #elif defined(USE_KQUEUE_FOR_THREADPOOL)
501 data->event_system = KQUEUE_BACKEND;
503 data->event_system = POLL_BACKEND;
505 if (g_getenv ("MONO_DISABLE_AIO") != NULL)
506 data->event_system = POLL_BACKEND;
508 init_event_system (data);
509 mono_thread_create_internal (mono_get_root_domain (), data->wait, data, TRUE, SMALL_STACK);
510 mono_mutex_unlock (&data->io_lock);
512 threadpool_start_thread (&async_io_tp);
516 socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
519 SocketIOData *data = &socket_io_data;
524 socket_io_init (&socket_io_data);
525 if (mono_runtime_is_shutting_down () || data->inited == 3 || data->sock_to_state == NULL)
527 if (async_tp.pool_status == 2)
530 MONO_OBJECT_SETREF (state, ares, ares);
532 fd = GPOINTER_TO_INT (state->handle);
533 mono_mutex_lock (&data->io_lock);
534 if (data->sock_to_state == NULL) {
535 mono_mutex_unlock (&data->io_lock);
538 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
540 list = mono_mlist_alloc ((MonoObject*)state);
543 list = mono_mlist_append (list, (MonoObject*)state);
547 mono_g_hash_table_replace (data->sock_to_state, state->handle, list);
548 ievt = get_events_from_list (list);
549 /* The modify function leaves the io_lock critical section. */
550 data->modify (data, fd, state->operation, ievt, is_new);
553 #ifndef DISABLE_SOCKETS
555 socket_io_filter (MonoObject *target, MonoObject *state)
558 MonoSocketAsyncResult *sock_res;
562 if (target == NULL || state == NULL)
565 domain = target->vtable->domain;
566 klass = target->vtable->klass;
567 if (socket_async_call_klass == NULL && is_socketasynccall (domain, klass))
568 socket_async_call_klass = klass;
570 if (process_async_call_klass == NULL && is_sdp_asyncreadhandler (domain, klass))
571 process_async_call_klass = klass;
573 if (klass != socket_async_call_klass && klass != process_async_call_klass)
576 sock_res = (MonoSocketAsyncResult *) state;
577 op = sock_res->operation;
578 if (op < AIO_OP_FIRST || op >= AIO_OP_LAST)
583 #endif /* !DISABLE_SOCKETS */
585 /* Returns the exception thrown when invoking, if any */
587 mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares)
589 MonoObject *exc = NULL;
591 mono_async_result_invoke (ares, &exc);
594 InterlockedDecrement (&tp->njobs);
597 InterlockedIncrement (&tp->nexecuted);
599 if (InterlockedDecrement (&monitor_njobs) == 0)
600 monitor_state = MONITOR_STATE_FALLING_ASLEEP;
606 threadpool_start_idle_threads (ThreadPool *tp)
611 stack_size = (!tp->is_io) ? 0 : SMALL_STACK;
615 if (n >= tp->min_threads)
617 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n)
620 #ifndef DISABLE_PERFCOUNTERS
621 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
623 mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE, stack_size);
629 threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer))
631 memset (tp, 0, sizeof (ThreadPool));
632 tp->min_threads = min_threads;
633 tp->max_threads = max_threads;
634 tp->async_invoke = async_invoke;
635 tp->queue = mono_cq_create ();
636 MONO_SEM_INIT (&tp->new_job, 0);
639 #ifndef DISABLE_PERFCOUNTERS
641 init_perf_counter (const char *category, const char *counter)
643 MonoString *category_str;
644 MonoString *counter_str;
650 if (category == NULL || counter == NULL)
652 root = mono_get_root_domain ();
653 category_str = mono_string_new (root, category);
654 counter_str = mono_string_new (root, counter);
655 machine = mono_string_new (root, ".");
656 return mono_perfcounter_get_impl (category_str, counter_str, NULL, machine, &type, &custom);
662 print_pool_info (ThreadPool *tp)
665 // if (tp->tail - tp->head == 0)
668 g_print ("Pool status? %d\n", InterlockedCompareExchange (&tp->pool_status, 0, 0));
669 g_print ("Min. threads: %d\n", InterlockedCompareExchange (&tp->min_threads, 0, 0));
670 g_print ("Max. threads: %d\n", InterlockedCompareExchange (&tp->max_threads, 0, 0));
671 g_print ("nthreads: %d\n", InterlockedCompareExchange (&tp->nthreads, 0, 0));
672 g_print ("busy threads: %d\n", InterlockedCompareExchange (&tp->busy_threads, 0, 0));
673 g_print ("Waiting: %d\n", InterlockedCompareExchange (&tp->waiting, 0, 0));
674 g_print ("Queued: %d\n", (tp->tail - tp->head));
675 if (tp == &async_tp) {
677 mono_mutex_lock (&wsqs_lock);
678 for (i = 0; i < wsqs->len; i++) {
679 g_print ("\tWSQ %d: %d\n", i, mono_wsq_count (g_ptr_array_index (wsqs, i)));
681 mono_mutex_unlock (&wsqs_lock);
683 g_print ("\tSockets: %d\n", mono_g_hash_table_size (socket_io_data.sock_to_state));
685 g_print ("-------------\n");
689 signal_handler (int signo)
694 g_print ("\n-----Non-IO-----\n");
695 print_pool_info (tp);
697 g_print ("\n-----IO-----\n");
698 print_pool_info (tp);
703 #define SAMPLES_PERIOD 500
704 #define HISTORY_SIZE 10
705 /* number of iteration without any jobs
706 in the queue before going to sleep */
707 #define NUM_WAITING_ITERATIONS 10
717 * - 1 if the number of threads should increase
718 * - 0 if it should not change
719 * - -1 if it should decrease
720 * - -2 in case of error
723 monitor_heuristic (gint16 *current, gint16 *history_size, SamplesHistory *history, ThreadPool *tp)
726 gint8 decision G_GNUC_UNUSED;
728 gboolean all_waitsleepjoin;
729 MonoInternalThread *thread;
732 * The following heuristic tries to approach the optimal number of threads to maximize jobs throughput. To
733 * achieve this, it simply stores the number of jobs executed (nexecuted), the number of Threads (nthreads)
734 * and the decision (nthreads_diff) for the past HISTORY_SIZE periods of time, each period being of
735 * duration SAMPLES_PERIOD ms. This history gives us an insight into what happened, and to see if we should
736 * increase or reduce the number of threads by comparing the last period (current) to the best one.
738 * The algorithm can be describe as following :
739 * - if we have a better throughput than the best period : we should either increase the number of threads
740 * in case we already have more threads, either reduce the number of threads if we have less threads; this
741 * is equivalent to move away from the number of threads of the best period, because we are currently better
742 * - if we have a worse throughput than the best period : we should either decrease the number of threads if
743 * we have more threads, either increase the number of threads if we have less threads; this is equivalent
744 * to get closer to the number of threads of the best period, because we are currently worse
747 *history_size = MIN (*history_size + 1, HISTORY_SIZE);
748 cur = *current = (*current + 1) % *history_size;
750 history [cur].nthreads = tp->nthreads;
751 history [cur].nexecuted = InterlockedExchange (&tp->nexecuted, 0);
754 /* if we have waiting thread in the pool, then do not create a new one */
755 history [cur].nthreads_diff = tp->waiting > 1 ? -1 : 0;
757 } else if (tp->nthreads < tp->min_threads) {
758 history [cur].nthreads_diff = 1;
760 } else if (*history_size <= 1) {
761 /* first iteration, let's add a thread by default */
762 history [cur].nthreads_diff = 1;
765 mono_mutex_lock (&threads_lock);
766 if (threads == NULL) {
767 mono_mutex_unlock (&threads_lock);
770 all_waitsleepjoin = TRUE;
771 for (i = 0; i < threads->len; ++i) {
772 thread = g_ptr_array_index (threads, i);
773 if (!(thread->state & ThreadState_WaitSleepJoin)) {
774 all_waitsleepjoin = FALSE;
778 mono_mutex_unlock (&threads_lock);
780 if (all_waitsleepjoin) {
781 /* we might be in a condition of starvation/deadlock with tasks waiting for each others */
782 history [cur].nthreads_diff = 1;
785 max = cur == 0 ? 1 : 0;
786 for (i = 0; i < *history_size; i++) {
789 if (history [i].nexecuted > history [max].nexecuted)
793 if (history [cur].nexecuted >= history [max].nexecuted) {
794 /* we improved the situation, let's continue ! */
795 history [cur].nthreads_diff = history [cur].nthreads >= history [max].nthreads ? 1 : -1;
798 /* we made it worse, let's return to previous situation */
799 history [cur].nthreads_diff = history [cur].nthreads >= history [max].nthreads ? -1 : 1;
806 printf ("monitor_thread: decision: %1d, history [current]: {nexecuted: %5d, nthreads: %3d, waiting: %2d, nthreads_diff: %2d}, history [max]: {nexecuted: %5d, nthreads: %3d}\n",
807 decision, history [cur].nexecuted, history [cur].nthreads, tp->waiting, history [cur].nthreads_diff, history [max].nexecuted, history [max].nthreads);
810 return history [cur].nthreads_diff;
814 monitor_thread (gpointer unused)
816 ThreadPool *pools [2];
817 MonoInternalThread *thread;
821 gint8 num_waiting_iterations = 0;
823 gint16 history_size = 0, current = -1;
824 SamplesHistory *history = malloc (sizeof (SamplesHistory) * HISTORY_SIZE);
826 pools [0] = &async_tp;
827 pools [1] = &async_io_tp;
828 thread = mono_thread_internal_current ();
829 ves_icall_System_Threading_Thread_SetName_internal (thread, mono_string_new (mono_domain_get (), "Threadpool monitor"));
832 i = 10; //number of spurious awakes we tolerate before doing a round of rebalancing.
833 mono_gc_set_skip_thread (TRUE);
836 ts = mono_msec_ticks ();
837 if (SleepEx (ms, TRUE) == 0)
839 ms -= (mono_msec_ticks () - ts);
840 if (mono_runtime_is_shutting_down ())
842 check_for_interruption_critical ();
843 } while (ms > 0 && i--);
844 mono_gc_set_skip_thread (FALSE);
846 if (mono_runtime_is_shutting_down ())
852 /* threadpool is cleaning up */
853 if (async_tp.pool_status == 2 || async_io_tp.pool_status == 2)
856 switch (monitor_state) {
857 case MONITOR_STATE_AWAKE:
858 num_waiting_iterations = 0;
860 case MONITOR_STATE_FALLING_ASLEEP:
861 if (++num_waiting_iterations == NUM_WAITING_ITERATIONS) {
862 if (monitor_state == MONITOR_STATE_FALLING_ASLEEP && InterlockedCompareExchange (&monitor_state, MONITOR_STATE_SLEEPING, MONITOR_STATE_FALLING_ASLEEP) == MONITOR_STATE_FALLING_ASLEEP) {
863 MONO_SEM_WAIT (&monitor_sem);
865 num_waiting_iterations = 0;
871 case MONITOR_STATE_SLEEPING:
872 g_assert_not_reached ();
875 for (i = 0; i < 2; i++) {
880 if (!tp->waiting && mono_cq_count (tp->queue) > 0)
881 threadpool_start_thread (tp);
883 gint8 nthreads_diff = monitor_heuristic (¤t, &history_size, history, tp);
885 if (nthreads_diff == 1)
886 threadpool_start_thread (tp);
887 else if (nthreads_diff == -1)
888 threadpool_kill_thread (tp);
895 mono_thread_pool_init_tls (void)
897 if (use_ms_threadpool ()) {
898 mono_threadpool_ms_init_tls ();
906 mono_thread_pool_init (void)
908 gint threads_per_cpu = 1;
913 if (use_ms_threadpool ()) {
914 mono_threadpool_ms_init ();
918 cpu_count = mono_cpu_count ();
923 result = InterlockedCompareExchange (&tp_inited, 1, 0);
932 MONO_GC_REGISTER_ROOT_FIXED (socket_io_data.sock_to_state);
933 mono_mutex_init_recursive (&socket_io_data.io_lock);
934 if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
935 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
936 if (threads_per_cpu < 1)
940 thread_count = MIN (cpu_count * threads_per_cpu, 100 * cpu_count);
941 threadpool_init (&async_tp, thread_count, MAX (100 * cpu_count, thread_count), async_invoke_thread);
942 threadpool_init (&async_io_tp, cpu_count * 2, cpu_count * 4, async_invoke_thread);
943 async_io_tp.is_io = TRUE;
945 async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
946 g_assert (async_call_klass);
948 mono_mutex_init (&threads_lock);
949 threads = g_ptr_array_sized_new (thread_count);
952 mono_mutex_init_recursive (&wsqs_lock);
953 wsqs = g_ptr_array_sized_new (MAX (100 * cpu_count, thread_count));
955 #ifndef DISABLE_PERFCOUNTERS
956 async_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "Work Items Added");
957 g_assert (async_tp.pc_nitems);
959 async_io_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "IO Work Items Added");
960 g_assert (async_io_tp.pc_nitems);
962 async_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of Threads");
963 g_assert (async_tp.pc_nthreads);
965 async_io_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of IO Threads");
966 g_assert (async_io_tp.pc_nthreads);
970 signal (SIGALRM, signal_handler);
974 MONO_SEM_INIT (&monitor_sem, 0);
975 monitor_state = MONITOR_STATE_AWAKE;
979 static MonoAsyncResult *
980 create_simple_asyncresult (MonoObject *target, MonoObject *state)
982 MonoDomain *domain = mono_domain_get ();
983 MonoAsyncResult *ares;
985 /* Don't call mono_async_result_new() to avoid capturing the context */
986 ares = (MonoAsyncResult *) mono_object_new (domain, mono_defaults.asyncresult_class);
987 MONO_OBJECT_SETREF (ares, async_delegate, target);
988 MONO_OBJECT_SETREF (ares, async_state, state);
993 icall_append_io_job (MonoObject *target, MonoSocketAsyncResult *state)
995 MonoAsyncResult *ares;
997 ares = create_simple_asyncresult (target, (MonoObject *) state);
999 if (use_ms_threadpool ()) {
1000 #ifndef DISABLE_SOCKETS
1001 mono_threadpool_ms_io_add (ares, state);
1006 socket_io_add (ares, state);
1010 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
1014 MonoAsyncResult *ares;
1017 if (use_ms_threadpool ())
1018 return mono_threadpool_ms_add (target, msg, async_callback, state);
1020 domain = mono_domain_get ();
1022 ac = (MonoAsyncCall*)mono_object_new (domain, async_call_klass);
1023 MONO_OBJECT_SETREF (ac, msg, msg);
1024 MONO_OBJECT_SETREF (ac, state, state);
1026 if (async_callback) {
1027 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
1028 MONO_OBJECT_SETREF (ac, cb_target, async_callback);
1031 ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
1032 MONO_OBJECT_SETREF (ares, async_delegate, target);
1034 #ifndef DISABLE_SOCKETS
1035 if (socket_io_filter (target, state)) {
1036 socket_io_add (ares, (MonoSocketAsyncResult *) state);
1040 threadpool_append_job (&async_tp, (MonoObject *) ares);
1045 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1050 if (use_ms_threadpool ()) {
1051 return mono_threadpool_ms_finish (ares, out_args, exc);
1057 /* check if already finished */
1058 mono_monitor_enter ((MonoObject *) ares);
1060 if (ares->endinvoke_called) {
1061 *exc = (MonoObject *) mono_get_exception_invalid_operation (NULL);
1062 mono_monitor_exit ((MonoObject *) ares);
1066 ares->endinvoke_called = 1;
1067 /* wait until we are really finished */
1068 if (!ares->completed) {
1069 if (ares->handle == NULL) {
1070 wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1071 g_assert(wait_event != 0);
1072 MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), wait_event));
1074 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
1076 mono_monitor_exit ((MonoObject *) ares);
1077 MONO_PREPARE_BLOCKING
1078 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
1079 MONO_FINISH_BLOCKING
1081 mono_monitor_exit ((MonoObject *) ares);
1084 ac = (MonoAsyncCall *) ares->object_data;
1085 g_assert (ac != NULL);
1086 *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1087 *out_args = ac->out_args;
1093 threadpool_kill_idle_threads (ThreadPool *tp)
1097 n = (gint) InterlockedCompareExchange (&tp->max_threads, 0, -1);
1100 MONO_SEM_POST (&tp->new_job);
1105 mono_thread_pool_cleanup (void)
1107 if (use_ms_threadpool ()) {
1108 mono_threadpool_ms_cleanup ();
1112 if (InterlockedExchange (&async_io_tp.pool_status, 2) == 1) {
1113 socket_io_cleanup (&socket_io_data); /* Empty when DISABLE_SOCKETS is defined */
1114 threadpool_kill_idle_threads (&async_io_tp);
1117 if (async_io_tp.queue != NULL) {
1118 MONO_SEM_DESTROY (&async_io_tp.new_job);
1119 threadpool_free_queue (&async_io_tp);
1123 if (InterlockedExchange (&async_tp.pool_status, 2) == 1) {
1124 threadpool_kill_idle_threads (&async_tp);
1125 threadpool_free_queue (&async_tp);
1129 mono_mutex_lock (&threads_lock);
1131 g_ptr_array_free (threads, FALSE);
1133 mono_mutex_unlock (&threads_lock);
1137 mono_mutex_lock (&wsqs_lock);
1138 mono_wsq_cleanup ();
1140 g_ptr_array_free (wsqs, TRUE);
1142 mono_mutex_unlock (&wsqs_lock);
1143 MONO_SEM_DESTROY (&async_tp.new_job);
1146 MONO_SEM_DESTROY (&monitor_sem);
1150 threadpool_start_thread (ThreadPool *tp)
1154 MonoInternalThread *thread;
1156 stack_size = (!tp->is_io) ? 0 : SMALL_STACK;
1157 while (!mono_runtime_is_shutting_down () && (n = tp->nthreads) < tp->max_threads) {
1158 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n) {
1159 #ifndef DISABLE_PERFCOUNTERS
1160 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
1163 thread = mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE, stack_size);
1165 mono_mutex_lock (&threads_lock);
1166 thread = mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE, stack_size);
1167 g_assert (threads != NULL);
1168 g_ptr_array_add (threads, thread);
1169 mono_mutex_unlock (&threads_lock);
1179 pulse_on_new_job (ThreadPool *tp)
1182 MONO_SEM_POST (&tp->new_job);
1186 threadpool_kill_thread (ThreadPool *tp)
1188 if (tp->destroy_thread == 0 && InterlockedCompareExchange (&tp->destroy_thread, 1, 0) == 0)
1189 pulse_on_new_job (tp);
1193 icall_append_job (MonoObject *ar)
1195 threadpool_append_jobs (&async_tp, &ar, 1);
1199 threadpool_append_job (ThreadPool *tp, MonoObject *ar)
1201 threadpool_append_jobs (tp, &ar, 1);
1205 threadpool_append_async_io_jobs (MonoObject **jobs, gint njobs)
1207 threadpool_append_jobs (&async_io_tp, jobs, njobs);
1211 threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs)
1216 if (mono_runtime_is_shutting_down ())
1219 if (tp->pool_status == 0 && InterlockedCompareExchange (&tp->pool_status, 1, 0) == 0) {
1221 monitor_internal_thread = mono_thread_create_internal (mono_get_root_domain (), monitor_thread, NULL, TRUE, SMALL_STACK);
1222 monitor_internal_thread->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
1223 threadpool_start_thread (tp);
1225 /* Create on demand up to min_threads to avoid startup penalty for apps that don't use
1226 * the threadpool that much
1228 if (mono_config_is_server_mode ()) {
1229 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, tp, TRUE, SMALL_STACK);
1233 InterlockedAdd (&monitor_njobs, njobs);
1235 if (monitor_state == MONITOR_STATE_SLEEPING && InterlockedCompareExchange (&monitor_state, MONITOR_STATE_AWAKE, MONITOR_STATE_SLEEPING) == MONITOR_STATE_SLEEPING)
1236 MONO_SEM_POST (&monitor_sem);
1238 if (monitor_state == MONITOR_STATE_FALLING_ASLEEP)
1239 InterlockedCompareExchange (&monitor_state, MONITOR_STATE_AWAKE, MONITOR_STATE_FALLING_ASLEEP);
1241 for (i = 0; i < njobs; i++) {
1243 if (ar == NULL || mono_domain_is_unloading (ar->vtable->domain))
1244 continue; /* Might happen when cleaning domain jobs */
1245 threadpool_jobs_inc (ar);
1246 #ifndef DISABLE_PERFCOUNTERS
1247 mono_perfcounter_update_value (tp->pc_nitems, TRUE, 1);
1249 if (!tp->is_io && mono_wsq_local_push (ar))
1252 mono_cq_enqueue (tp->queue, ar);
1256 InterlockedAdd (&tp->njobs, njobs);
1259 for (i = 0; tp->waiting > 0 && i < MIN(njobs, tp->max_threads); i++)
1260 pulse_on_new_job (tp);
1264 threadpool_clear_queue (ThreadPool *tp, MonoDomain *domain)
1267 MonoMList *other = NULL;
1268 MonoCQ *queue = tp->queue;
1273 while (mono_cq_dequeue (queue, &obj)) {
1276 if (obj->vtable->domain != domain)
1277 other = mono_mlist_prepend (other, obj);
1278 threadpool_jobs_dec (obj);
1281 if (mono_runtime_is_shutting_down ())
1285 threadpool_append_job (tp, (MonoObject *) mono_mlist_get_data (other));
1286 other = mono_mlist_next (other);
1291 remove_sockstate_for_domain (gpointer key, gpointer value, gpointer user_data)
1293 MonoMList *list = value;
1294 gboolean remove = FALSE;
1296 MonoObject *data = mono_mlist_get_data (list);
1297 if (mono_object_domain (data) == user_data) {
1299 mono_mlist_set_data (list, NULL);
1301 list = mono_mlist_next (list);
1303 //FIXME is there some sort of additional unregistration we need to perform here?
1308 * Clean up the threadpool of all domain jobs.
1309 * Can only be called as part of the domain unloading process as
1310 * it will wait for all jobs to be visible to the interruption code.
1313 mono_thread_pool_remove_domain_jobs (MonoDomain *domain, int timeout)
1319 if (use_ms_threadpool ()) {
1320 return mono_threadpool_ms_remove_domain_jobs (domain, timeout);
1326 g_assert (domain->state == MONO_APPDOMAIN_UNLOADING);
1328 threadpool_clear_queue (&async_tp, domain);
1329 threadpool_clear_queue (&async_io_tp, domain);
1331 mono_mutex_lock (&socket_io_data.io_lock);
1332 if (socket_io_data.sock_to_state)
1333 mono_g_hash_table_foreach_remove (socket_io_data.sock_to_state, remove_sockstate_for_domain, domain);
1335 mono_mutex_unlock (&socket_io_data.io_lock);
1338 * There might be some threads out that could be about to execute stuff from the given domain.
1339 * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
1341 sem_handle = CreateSemaphore (NULL, 0, 1, NULL);
1343 domain->cleanup_semaphore = sem_handle;
1345 * The memory barrier here is required to have global ordering between assigning to cleanup_semaphone
1346 * and reading threadpool_jobs.
1347 * Otherwise this thread could read a stale version of threadpool_jobs and wait forever.
1349 mono_memory_write_barrier ();
1351 if (domain->threadpool_jobs && timeout != -1)
1352 start_time = mono_msec_ticks ();
1353 while (domain->threadpool_jobs) {
1354 MONO_PREPARE_BLOCKING
1355 WaitForSingleObject (sem_handle, timeout);
1356 MONO_FINISH_BLOCKING
1357 if (timeout != -1 && (mono_msec_ticks () - start_time) > timeout) {
1363 domain->cleanup_semaphore = NULL;
1364 CloseHandle (sem_handle);
1369 threadpool_free_queue (ThreadPool *tp)
1371 mono_cq_destroy (tp->queue);
1376 mono_thread_pool_is_queue_array (MonoArray *o)
1378 if (use_ms_threadpool ()) {
1379 return mono_threadpool_ms_is_queue_array (o);
1382 // gpointer obj = o;
1384 // FIXME: need some fix in sgen code.
1394 mono_mutex_lock (&wsqs_lock);
1395 wsq = mono_wsq_create ();
1397 mono_mutex_unlock (&wsqs_lock);
1400 for (i = 0; i < wsqs->len; i++) {
1401 if (g_ptr_array_index (wsqs, i) == NULL) {
1402 wsqs->pdata [i] = wsq;
1403 mono_mutex_unlock (&wsqs_lock);
1407 g_ptr_array_add (wsqs, wsq);
1408 mono_mutex_unlock (&wsqs_lock);
1413 remove_wsq (MonoWSQ *wsq)
1420 mono_mutex_lock (&wsqs_lock);
1422 mono_mutex_unlock (&wsqs_lock);
1425 g_ptr_array_remove_fast (wsqs, wsq);
1428 * Only clean this up when shutting down, any other case will error out
1429 * if we're removing a queue that still has work items.
1431 if (mono_runtime_is_shutting_down ()) {
1432 while (mono_wsq_local_pop (&data)) {
1433 threadpool_jobs_dec (data);
1437 mono_wsq_destroy (wsq);
1438 mono_mutex_unlock (&wsqs_lock);
1442 try_steal (MonoWSQ *local_wsq, gpointer *data, gboolean retry)
1447 if (wsqs == NULL || data == NULL || *data != NULL)
1452 if (mono_runtime_is_shutting_down ())
1455 MONO_PREPARE_BLOCKING
1456 mono_mutex_lock (&wsqs_lock);
1457 MONO_FINISH_BLOCKING
1458 for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
1461 wsq = wsqs->pdata [i];
1462 if (wsq == local_wsq || mono_wsq_count (wsq) == 0)
1464 mono_wsq_try_steal (wsqs->pdata [i], data, ms);
1465 if (*data != NULL) {
1466 mono_mutex_unlock (&wsqs_lock);
1470 mono_mutex_unlock (&wsqs_lock);
1472 } while (retry && ms < 11);
1476 dequeue_or_steal (ThreadPool *tp, gpointer *data, MonoWSQ *local_wsq)
1478 MonoCQ *queue = tp->queue;
1479 if (mono_runtime_is_shutting_down () || !queue)
1481 mono_cq_dequeue (queue, (MonoObject **) data);
1482 if (!tp->is_io && !*data)
1483 try_steal (local_wsq, data, FALSE);
1484 return (*data != NULL);
1488 should_i_die (ThreadPool *tp)
1490 gboolean result = FALSE;
1491 if (tp->destroy_thread == 1 && InterlockedCompareExchange (&tp->destroy_thread, 0, 1) == 1)
1492 result = (tp->nthreads > tp->min_threads);
1497 set_tp_thread_info (ThreadPool *tp)
1500 MonoInternalThread *thread = mono_thread_internal_current ();
1502 mono_profiler_thread_start (thread->tid);
1503 name = (tp->is_io) ? "IO Threadpool worker" : "Threadpool worker";
1504 mono_thread_set_name_internal (thread, mono_string_new (mono_domain_get (), name), FALSE);
1508 clear_thread_state (void)
1510 MonoInternalThread *thread = mono_thread_internal_current ();
1511 /* If the callee changes the background status, set it back to TRUE */
1512 mono_thread_clr_state (thread , ~ThreadState_Background);
1513 if (!mono_thread_test_state (thread , ThreadState_Background))
1514 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
1518 check_for_interruption_critical (void)
1520 MonoInternalThread *thread;
1521 /*RULE NUMBER ONE OF SKIP_THREAD: NEVER POKE MANAGED STATE.*/
1522 mono_gc_set_skip_thread (FALSE);
1524 thread = mono_thread_internal_current ();
1525 if (THREAD_WANTS_A_BREAK (thread))
1526 mono_thread_interruption_checkpoint ();
1528 /*RULE NUMBER TWO OF SKIP_THREAD: READ RULE NUMBER ONE.*/
1529 mono_gc_set_skip_thread (TRUE);
1533 fire_profiler_thread_end (void)
1535 MonoInternalThread *thread = mono_thread_internal_current ();
1536 mono_profiler_thread_end (thread->tid);
1540 async_invoke_thread (gpointer data)
1552 set_tp_thread_info (tp);
1555 tp_start_func (tp_hooks_user_data);
1559 MonoAsyncResult *ar;
1561 gboolean is_io_task;
1566 ar = (MonoAsyncResult *) data;
1568 InterlockedIncrement (&tp->busy_threads);
1569 domain = ((MonoObject *)ar)->vtable->domain;
1570 #ifndef DISABLE_SOCKETS
1571 klass = ((MonoObject *) data)->vtable->klass;
1572 is_io_task = !is_corlib_asyncresult (domain, klass);
1575 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1576 is_socket = is_socketasyncresult (domain, klass);
1578 switch (state->operation) {
1579 case AIO_OP_RECEIVE:
1580 state->total = ICALL_RECV (state);
1583 state->total = ICALL_SEND (state);
1588 /* worker threads invokes methods in different domains,
1589 * so we need to set the right domain here */
1592 if (mono_domain_is_unloading (domain) || mono_runtime_is_shutting_down ()) {
1593 threadpool_jobs_dec ((MonoObject *)ar);
1596 InterlockedDecrement (&tp->busy_threads);
1598 mono_thread_push_appdomain_ref (domain);
1599 if (threadpool_jobs_dec ((MonoObject *)ar)) {
1602 mono_thread_pop_appdomain_ref ();
1603 InterlockedDecrement (&tp->busy_threads);
1607 if (mono_domain_set (domain, FALSE)) {
1610 if (tp_item_begin_func)
1611 tp_item_begin_func (tp_item_user_data);
1613 exc = mono_async_invoke (tp, ar);
1614 if (tp_item_end_func)
1615 tp_item_end_func (tp_item_user_data);
1617 mono_internal_thread_unhandled_exception (exc);
1618 if (is_socket && tp->is_io) {
1619 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1621 if (state->completed && state->callback) {
1622 MonoAsyncResult *cb_ares;
1623 cb_ares = create_simple_asyncresult ((MonoObject *) state->callback,
1624 (MonoObject *) state);
1625 icall_append_job ((MonoObject *) cb_ares);
1628 mono_domain_set (mono_get_root_domain (), TRUE);
1630 mono_thread_pop_appdomain_ref ();
1631 InterlockedDecrement (&tp->busy_threads);
1632 clear_thread_state ();
1638 must_die = should_i_die (tp);
1640 mono_wsq_suspend (wsq);
1642 if (tp->is_io || !mono_wsq_local_pop (&data))
1643 dequeue_or_steal (tp, &data, wsq);
1647 while (!must_die && !data && n_naps < 4) {
1650 InterlockedIncrement (&tp->waiting);
1652 // Another thread may have added a job into its wsq since the last call to dequeue_or_steal
1653 // Check all the queues again before entering the wait loop
1654 dequeue_or_steal (tp, &data, wsq);
1656 InterlockedDecrement (&tp->waiting);
1660 mono_gc_set_skip_thread (TRUE);
1662 #if defined(__OpenBSD__)
1663 while (mono_cq_count (tp->queue) == 0 && (res = mono_sem_wait (&tp->new_job, TRUE)) == -1) {// && errno == EINTR) {
1665 while (mono_cq_count (tp->queue) == 0 && (res = mono_sem_timedwait (&tp->new_job, 2000, TRUE)) == -1) {// && errno == EINTR) {
1667 if (mono_runtime_is_shutting_down ())
1669 check_for_interruption_critical ();
1671 InterlockedDecrement (&tp->waiting);
1673 mono_gc_set_skip_thread (FALSE);
1675 if (mono_runtime_is_shutting_down ())
1677 must_die = should_i_die (tp);
1678 dequeue_or_steal (tp, &data, wsq);
1682 if (!data && !tp->is_io && !mono_runtime_is_shutting_down ()) {
1683 mono_wsq_local_pop (&data);
1684 if (data && must_die) {
1685 InterlockedCompareExchange (&tp->destroy_thread, 1, 0);
1686 pulse_on_new_job (tp);
1695 down = mono_runtime_is_shutting_down ();
1696 if (!down && nt <= tp->min_threads)
1698 if (down || InterlockedCompareExchange (&tp->nthreads, nt - 1, nt) == nt) {
1699 #ifndef DISABLE_PERFCOUNTERS
1700 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, -1);
1706 fire_profiler_thread_end ();
1709 tp_finish_func (tp_hooks_user_data);
1713 mono_mutex_lock (&threads_lock);
1715 g_ptr_array_remove_fast (threads, mono_thread_current ()->internal_thread);
1716 mono_mutex_unlock (&threads_lock);
1726 g_assert_not_reached ();
1730 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
1732 *workerThreads = async_tp.max_threads - async_tp.busy_threads;
1733 *completionPortThreads = async_io_tp.max_threads - async_io_tp.busy_threads;
1737 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
1739 *workerThreads = async_tp.max_threads;
1740 *completionPortThreads = async_io_tp.max_threads;
1744 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
1746 *workerThreads = async_tp.min_threads;
1747 *completionPortThreads = async_io_tp.min_threads;
1751 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
1754 gint max_io_threads;
1756 max_threads = async_tp.max_threads;
1757 if (workerThreads <= 0 || workerThreads > max_threads)
1760 max_io_threads = async_io_tp.max_threads;
1761 if (completionPortThreads <= 0 || completionPortThreads > max_io_threads)
1764 InterlockedExchange (&async_tp.min_threads, workerThreads);
1765 InterlockedExchange (&async_io_tp.min_threads, completionPortThreads);
1766 if (workerThreads > async_tp.nthreads)
1767 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_tp, TRUE, SMALL_STACK);
1768 if (completionPortThreads > async_io_tp.nthreads)
1769 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_io_tp, TRUE, SMALL_STACK);
1774 ves_icall_System_Threading_ThreadPool_SetMaxThreads (gint workerThreads, gint completionPortThreads)
1777 gint min_io_threads;
1780 cpu_count = mono_cpu_count ();
1781 min_threads = async_tp.min_threads;
1782 if (workerThreads < min_threads || workerThreads < cpu_count)
1785 /* We don't really have the concept of completion ports. Do we care here? */
1786 min_io_threads = async_io_tp.min_threads;
1787 if (completionPortThreads < min_io_threads || completionPortThreads < cpu_count)
1790 InterlockedExchange (&async_tp.max_threads, workerThreads);
1791 InterlockedExchange (&async_io_tp.max_threads, completionPortThreads);
1796 * mono_install_threadpool_thread_hooks
1797 * @start_func: the function to be called right after a new threadpool thread is created. Can be NULL.
1798 * @finish_func: the function to be called right before a thredpool thread is exiting. Can be NULL.
1799 * @user_data: argument passed to @start_func and @finish_func.
1801 * @start_fun will be called right after a threadpool thread is created and @finish_func right before a threadpool thread exits.
1802 * The calls will be made from the thread itself.
1805 mono_install_threadpool_thread_hooks (MonoThreadPoolFunc start_func, MonoThreadPoolFunc finish_func, gpointer user_data)
1807 tp_start_func = start_func;
1808 tp_finish_func = finish_func;
1809 tp_hooks_user_data = user_data;
1813 * mono_install_threadpool_item_hooks
1814 * @begin_func: the function to be called before a threadpool work item processing starts.
1815 * @end_func: the function to be called after a threadpool work item is finished.
1816 * @user_data: argument passed to @begin_func and @end_func.
1818 * The calls will be made from the thread itself and from the same AppDomain
1819 * where the work item was executed.
1823 mono_install_threadpool_item_hooks (MonoThreadPoolItemFunc begin_func, MonoThreadPoolItemFunc end_func, gpointer user_data)
1825 tp_item_begin_func = begin_func;
1826 tp_item_end_func = end_func;
1827 tp_item_user_data = user_data;
1831 mono_internal_thread_unhandled_exception (MonoObject* exc)
1833 if (mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_CURRENT) {
1837 klass = exc->vtable->klass;
1838 unloaded = is_appdomainunloaded_exception (exc->vtable->domain, klass);
1839 if (!unloaded && klass != mono_defaults.threadabortexception_class) {
1840 mono_unhandled_exception (exc);
1841 if (mono_environment_exitcode_get () == 1)
1844 if (klass == mono_defaults.threadabortexception_class)
1845 mono_thread_internal_reset_abort (mono_thread_internal_current ());
1850 * Suspend creation of new threads.
1853 mono_thread_pool_suspend (void)
1855 if (use_ms_threadpool ()) {
1856 mono_threadpool_ms_suspend ();
1863 * Resume creation of new threads.
1866 mono_thread_pool_resume (void)
1868 if (use_ms_threadpool ()) {
1869 mono_threadpool_ms_resume ();