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-mlist.h>
23 #include <mono/metadata/mono-perfcounters.h>
24 #include <mono/metadata/socket-io.h>
25 #include <mono/metadata/mono-cq.h>
26 #include <mono/metadata/mono-wsq.h>
27 #include <mono/metadata/mono-ptr-array.h>
28 #include <mono/io-layer/io-layer.h>
29 #include <mono/utils/mono-time.h>
30 #include <mono/utils/mono-proclib.h>
31 #include <mono/utils/mono-semaphore.h>
32 #include <mono/utils/atomic.h>
34 #ifdef HAVE_SYS_TIME_H
37 #include <sys/types.h>
43 #ifdef HAVE_SYS_SOCKET_H
44 #include <sys/socket.h>
46 #include <mono/utils/mono-poll.h>
48 #include <sys/epoll.h>
51 #include <sys/event.h>
55 #ifndef DISABLE_SOCKETS
56 #include "mono/io-layer/socket-wrappers.h"
59 #include "threadpool.h"
61 #define THREAD_WANTS_A_BREAK(t) ((t->state & (ThreadState_StopRequested | \
62 ThreadState_SuspendRequested)) != 0)
64 #define SPIN_TRYLOCK(i) (InterlockedCompareExchange (&(i), 1, 0) == 0)
65 #define SPIN_LOCK(i) do { \
66 if (SPIN_TRYLOCK (i)) \
70 #define SPIN_UNLOCK(i) i = 0
71 #define SMALL_STACK (128 * (sizeof (gpointer) / 4) * 1024)
73 /* DEBUG: prints tp data every 2s */
76 /* mono_thread_pool_init called */
77 static volatile int tp_inited;
86 CRITICAL_SECTION io_lock; /* access to sock_to_state */
87 int inited; // 0 -> not initialized , 1->initializing, 2->initialized, 3->cleaned up
88 MonoGHashTable *sock_to_state;
92 void (*modify) (gpointer event_data, int fd, int operation, int events, gboolean is_new);
93 void (*wait) (gpointer sock_data);
94 void (*shutdown) (gpointer event_data);
97 static SocketIOData socket_io_data;
99 /* Keep in sync with the System.MonoAsyncCall class which provides GC tracking */
102 MonoMethodMessage *msg;
103 MonoMethod *cb_method;
104 MonoDelegate *cb_target;
112 MonoCQ *queue; /* GC root */
114 volatile gint waiting; /* threads waiting for a work item */
117 volatile gint pool_status; /* 0 -> not initialized, 1 -> initialized, 2 -> cleaning up */
118 /* min, max, n and busy -> Interlocked */
119 volatile gint min_threads;
120 volatile gint max_threads;
121 volatile gint nthreads;
122 volatile gint busy_threads;
124 void (*async_invoke) (gpointer data);
125 void *pc_nitems; /* Performance counter for total number of items in added */
126 void *pc_nthreads; /* Performance counter for total number of active threads */
128 volatile gint destroy_thread;
129 volatile gint ignore_times; /* Used when there's a thread being created or destroyed */
130 volatile gint sp_lock; /* spin lock used to protect ignore_times */
131 volatile gint64 last_check;
132 volatile gint64 time_sum;
138 static ThreadPool async_tp;
139 static ThreadPool async_io_tp;
141 static void async_invoke_thread (gpointer data);
142 static MonoObject *mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares);
143 static void threadpool_free_queue (ThreadPool *tp);
144 static void threadpool_append_job (ThreadPool *tp, MonoObject *ar);
145 static void threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs);
146 static void threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer));
147 static void threadpool_start_idle_threads (ThreadPool *tp);
148 static void threadpool_kill_idle_threads (ThreadPool *tp);
149 static gboolean threadpool_start_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);
156 static MonoClass *async_call_klass;
157 static MonoClass *socket_async_call_klass;
158 static MonoClass *process_async_call_klass;
160 static GPtrArray *wsqs;
161 CRITICAL_SECTION wsqs_lock;
162 static gboolean suspended;
165 static MonoThreadPoolFunc tp_start_func;
166 static MonoThreadPoolFunc tp_finish_func;
167 static gpointer tp_hooks_user_data;
168 static MonoThreadPoolItemFunc tp_item_begin_func;
169 static MonoThreadPoolItemFunc tp_item_end_func;
170 static gpointer tp_item_user_data;
180 AIO_OP_RECV_JUST_CALLBACK,
181 AIO_OP_SEND_JUST_CALLBACK,
185 AIO_OP_ACCEPTRECEIVE,
186 AIO_OP_RECEIVE_BUFFERS,
191 #include <mono/metadata/tpool-poll.c>
193 #include <mono/metadata/tpool-epoll.c>
194 #elif defined(USE_KQUEUE_FOR_THREADPOOL)
195 #include <mono/metadata/tpool-kqueue.c>
198 * Functions to check whenever a class is given system class. We need to cache things in MonoDomain since some of the
199 * assemblies can be unloaded.
203 is_system_type (MonoDomain *domain, MonoClass *klass)
205 if (domain->system_image == NULL)
206 domain->system_image = mono_image_loaded ("System");
208 return klass->image == domain->system_image;
212 is_corlib_type (MonoDomain *domain, MonoClass *klass)
214 return klass->image == mono_defaults.corlib;
218 * Note that we call it is_socket_type() where 'socket' refers to the image
219 * that contains the System.Net.Sockets.Socket type.
222 is_socket_type (MonoDomain *domain, MonoClass *klass)
224 return is_system_type (domain, klass);
227 #define check_type_cached(domain, ASSEMBLY, _class, _namespace, _name, loc) do { \
229 return *loc == _class; \
230 if (is_##ASSEMBLY##_type (domain, _class) && !strcmp (_name, _class->name) && !strcmp (_namespace, _class->name_space)) { \
237 #define check_corlib_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, corlib, _class, _namespace, _name, loc)
239 #define check_socket_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, socket, _class, _namespace, _name, loc)
241 #define check_system_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, system, _class, _namespace, _name, loc)
244 is_corlib_asyncresult (MonoDomain *domain, MonoClass *klass)
246 check_corlib_type_cached (domain, klass, "System.Runtime.Remoting.Messaging", "AsyncResult", &domain->corlib_asyncresult_class);
250 is_socket (MonoDomain *domain, MonoClass *klass)
252 check_socket_type_cached (domain, klass, "System.Net.Sockets", "Socket", &domain->socket_class);
256 is_socketasyncresult (MonoDomain *domain, MonoClass *klass)
258 return (klass->nested_in &&
259 is_socket (domain, klass->nested_in) &&
260 !strcmp (klass->name, "SocketAsyncResult"));
264 is_socketasynccall (MonoDomain *domain, MonoClass *klass)
266 return (klass->nested_in &&
267 is_socket (domain, klass->nested_in) &&
268 !strcmp (klass->name, "SocketAsyncCall"));
272 is_appdomainunloaded_exception (MonoDomain *domain, MonoClass *klass)
274 check_corlib_type_cached (domain, klass, "System", "AppDomainUnloadedException", &domain->ad_unloaded_ex_class);
278 is_sd_process (MonoDomain *domain, MonoClass *klass)
280 check_system_type_cached (domain, klass, "System.Diagnostics", "Process", &domain->process_class);
284 is_sdp_asyncreadhandler (MonoDomain *domain, MonoClass *klass)
287 return (klass->nested_in &&
288 is_sd_process (domain, klass->nested_in) &&
289 !strcmp (klass->name, "AsyncReadHandler"));
293 #ifdef DISABLE_SOCKETS
295 #define socket_io_cleanup(x)
298 get_event_from_state (MonoSocketAsyncResult *state)
300 g_assert_not_reached ();
305 get_events_from_list (MonoMList *list)
313 socket_io_cleanup (SocketIOData *data)
315 EnterCriticalSection (&data->io_lock);
316 if (data->inited != 2) {
317 LeaveCriticalSection (&data->io_lock);
321 data->shutdown (data->event_data);
322 LeaveCriticalSection (&data->io_lock);
326 get_event_from_state (MonoSocketAsyncResult *state)
328 switch (state->operation) {
331 case AIO_OP_RECV_JUST_CALLBACK:
332 case AIO_OP_RECEIVEFROM:
333 case AIO_OP_READPIPE:
334 case AIO_OP_ACCEPTRECEIVE:
335 case AIO_OP_RECEIVE_BUFFERS:
338 case AIO_OP_SEND_JUST_CALLBACK:
341 case AIO_OP_SEND_BUFFERS:
342 case AIO_OP_DISCONNECT:
344 default: /* Should never happen */
345 g_message ("get_event_from_state: unknown value in switch!!!");
351 get_events_from_list (MonoMList *list)
353 MonoSocketAsyncResult *state;
356 while (list && (state = (MonoSocketAsyncResult *)mono_mlist_get_data (list))) {
357 events |= get_event_from_state (state);
358 list = mono_mlist_next (list);
364 #define ICALL_RECV(x) ves_icall_System_Net_Sockets_Socket_Receive_internal (\
365 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
366 x->socket_flags, &x->error);
368 #define ICALL_SEND(x) ves_icall_System_Net_Sockets_Socket_Send_internal (\
369 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
370 x->socket_flags, &x->error);
372 #endif /* !DISABLE_SOCKETS */
375 threadpool_jobs_inc (MonoObject *obj)
378 InterlockedIncrement (&obj->vtable->domain->threadpool_jobs);
382 threadpool_jobs_dec (MonoObject *obj)
390 domain = obj->vtable->domain;
391 remaining_jobs = InterlockedDecrement (&domain->threadpool_jobs);
392 if (remaining_jobs == 0 && domain->cleanup_semaphore) {
393 ReleaseSemaphore (domain->cleanup_semaphore, 1, NULL);
400 get_io_event (MonoMList **list, gint event)
410 state = mono_mlist_get_data (current);
411 if (get_event_from_state ((MonoSocketAsyncResult *) state) == event)
416 current = mono_mlist_next (current);
421 mono_mlist_set_next (prev, mono_mlist_next (current));
423 *list = mono_mlist_next (*list);
431 * select/poll wake up when a socket is closed, but epoll just removes
432 * the socket from its internal list without notification.
435 mono_thread_pool_remove_socket (int sock)
438 MonoSocketAsyncResult *state;
441 if (socket_io_data.inited == 0)
444 EnterCriticalSection (&socket_io_data.io_lock);
445 if (socket_io_data.sock_to_state == NULL) {
446 LeaveCriticalSection (&socket_io_data.io_lock);
449 list = mono_g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
451 mono_g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
452 LeaveCriticalSection (&socket_io_data.io_lock);
455 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
456 if (state->operation == AIO_OP_RECEIVE)
457 state->operation = AIO_OP_RECV_JUST_CALLBACK;
458 else if (state->operation == AIO_OP_SEND)
459 state->operation = AIO_OP_SEND_JUST_CALLBACK;
461 ares = get_io_event (&list, MONO_POLLIN);
462 threadpool_append_job (&async_io_tp, ares);
464 ares = get_io_event (&list, MONO_POLLOUT);
465 threadpool_append_job (&async_io_tp, ares);
471 init_event_system (SocketIOData *data)
474 if (data->event_system == EPOLL_BACKEND) {
475 data->event_data = tp_epoll_init (data);
476 if (data->event_data == NULL) {
477 if (g_getenv ("MONO_DEBUG"))
478 g_message ("Falling back to poll()");
479 data->event_system = POLL_BACKEND;
482 #elif defined(USE_KQUEUE_FOR_THREADPOOL)
483 if (data->event_system == KQUEUE_BACKEND)
484 data->event_data = tp_kqueue_init (data);
486 if (data->event_system == POLL_BACKEND)
487 data->event_data = tp_poll_init (data);
491 socket_io_init (SocketIOData *data)
495 if (data->inited >= 2) // 2 -> initialized, 3-> cleaned up
498 inited = InterlockedCompareExchange (&data->inited, 1, 0);
501 if (data->inited >= 2)
507 EnterCriticalSection (&data->io_lock);
508 data->sock_to_state = mono_g_hash_table_new_type (g_direct_hash, g_direct_equal, MONO_HASH_VALUE_GC);
510 data->event_system = EPOLL_BACKEND;
511 #elif defined(USE_KQUEUE_FOR_THREADPOOL)
512 data->event_system = KQUEUE_BACKEND;
514 data->event_system = POLL_BACKEND;
516 if (g_getenv ("MONO_DISABLE_AIO") != NULL)
517 data->event_system = POLL_BACKEND;
519 init_event_system (data);
520 mono_thread_create_internal (mono_get_root_domain (), data->wait, data, TRUE, FALSE, SMALL_STACK);
521 LeaveCriticalSection (&data->io_lock);
523 threadpool_start_thread (&async_io_tp);
527 socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
530 SocketIOData *data = &socket_io_data;
535 socket_io_init (&socket_io_data);
536 if (mono_runtime_is_shutting_down () || data->inited == 3 || data->sock_to_state == NULL)
538 if (async_tp.pool_status == 2)
541 MONO_OBJECT_SETREF (state, ares, ares);
543 fd = GPOINTER_TO_INT (state->handle);
544 EnterCriticalSection (&data->io_lock);
545 if (data->sock_to_state == NULL) {
546 LeaveCriticalSection (&data->io_lock);
549 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
551 list = mono_mlist_alloc ((MonoObject*)state);
554 list = mono_mlist_append (list, (MonoObject*)state);
558 mono_g_hash_table_replace (data->sock_to_state, state->handle, list);
559 ievt = get_events_from_list (list);
560 LeaveCriticalSection (&data->io_lock);
561 data->modify (data->event_data, fd, state->operation, ievt, is_new);
564 #ifndef DISABLE_SOCKETS
566 socket_io_filter (MonoObject *target, MonoObject *state)
569 MonoSocketAsyncResult *sock_res;
573 if (target == NULL || state == NULL)
576 domain = target->vtable->domain;
577 klass = target->vtable->klass;
578 if (socket_async_call_klass == NULL && is_socketasynccall (domain, klass))
579 socket_async_call_klass = klass;
581 if (process_async_call_klass == NULL && is_sdp_asyncreadhandler (domain, klass))
582 process_async_call_klass = klass;
584 if (klass != socket_async_call_klass && klass != process_async_call_klass)
587 sock_res = (MonoSocketAsyncResult *) state;
588 op = sock_res->operation;
589 if (op < AIO_OP_FIRST || op >= AIO_OP_LAST)
594 #endif /* !DISABLE_SOCKETS */
596 /* Returns the exception thrown when invoking, if any */
598 mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares)
600 ASyncCall *ac = (ASyncCall *)ares->object_data;
601 MonoObject *res, *exc = NULL;
602 MonoArray *out_args = NULL;
603 HANDLE wait_event = NULL;
604 MonoInternalThread *thread = mono_thread_internal_current ();
606 if (ares->execution_context) {
607 /* use captured ExecutionContext (if available) */
608 MONO_OBJECT_SETREF (ares, original_context, mono_thread_get_execution_context ());
609 mono_thread_set_execution_context (ares->execution_context);
611 ares->original_context = NULL;
615 /* Fast path from ThreadPool.*QueueUserWorkItem */
616 void *pa = ares->async_state;
617 /* The debugger needs this */
618 thread->async_invoke_method = ((MonoDelegate*)ares->async_delegate)->method;
619 res = mono_runtime_delegate_invoke (ares->async_delegate, &pa, &exc);
620 thread->async_invoke_method = NULL;
622 MonoObject *cb_exc = NULL;
625 res = mono_message_invoke (ares->async_delegate, ac->msg, &exc, &out_args);
626 MONO_OBJECT_SETREF (ac, res, res);
627 MONO_OBJECT_SETREF (ac, msg->exc, exc);
628 MONO_OBJECT_SETREF (ac, out_args, out_args);
630 mono_monitor_enter ((MonoObject *) ares);
632 if (ares->handle != NULL)
633 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
634 mono_monitor_exit ((MonoObject *) ares);
635 /* notify listeners */
636 if (wait_event != NULL)
637 SetEvent (wait_event);
639 /* call async callback if cb_method != null*/
640 if (ac != NULL && ac->cb_method) {
643 thread->async_invoke_method = ac->cb_method;
644 mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &cb_exc);
645 thread->async_invoke_method = NULL;
652 /* restore original thread execution context if flow isn't suppressed, i.e. non null */
653 if (ares->original_context) {
654 mono_thread_set_execution_context (ares->original_context);
655 ares->original_context = NULL;
661 threadpool_start_idle_threads (ThreadPool *tp)
666 stack_size = (!tp->is_io) ? 0 : SMALL_STACK;
670 if (n >= tp->min_threads)
672 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n)
675 #ifndef DISABLE_PERFCOUNTERS
676 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
678 mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE, FALSE, stack_size);
684 threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer))
686 memset (tp, 0, sizeof (ThreadPool));
687 tp->min_threads = min_threads;
688 tp->max_threads = max_threads;
689 tp->async_invoke = async_invoke;
690 tp->queue = mono_cq_create ();
691 MONO_SEM_INIT (&tp->new_job, 0);
694 #ifndef DISABLE_PERFCOUNTERS
696 init_perf_counter (const char *category, const char *counter)
698 MonoString *category_str;
699 MonoString *counter_str;
705 if (category == NULL || counter == NULL)
707 root = mono_get_root_domain ();
708 category_str = mono_string_new (root, category);
709 counter_str = mono_string_new (root, counter);
710 machine = mono_string_new (root, ".");
711 return mono_perfcounter_get_impl (category_str, counter_str, NULL, machine, &type, &custom);
717 print_pool_info (ThreadPool *tp)
720 // if (tp->tail - tp->head == 0)
723 g_print ("Pool status? %d\n", InterlockedCompareExchange (&tp->pool_status, 0, 0));
724 g_print ("Min. threads: %d\n", InterlockedCompareExchange (&tp->min_threads, 0, 0));
725 g_print ("Max. threads: %d\n", InterlockedCompareExchange (&tp->max_threads, 0, 0));
726 g_print ("nthreads: %d\n", InterlockedCompareExchange (&tp->nthreads, 0, 0));
727 g_print ("busy threads: %d\n", InterlockedCompareExchange (&tp->busy_threads, 0, 0));
728 g_print ("Waiting: %d\n", InterlockedCompareExchange (&tp->waiting, 0, 0));
729 g_print ("Queued: %d\n", (tp->tail - tp->head));
730 if (tp == &async_tp) {
732 EnterCriticalSection (&wsqs_lock);
733 for (i = 0; i < wsqs->len; i++) {
734 g_print ("\tWSQ %d: %d\n", i, mono_wsq_count (g_ptr_array_index (wsqs, i)));
736 LeaveCriticalSection (&wsqs_lock);
738 g_print ("\tSockets: %d\n", mono_g_hash_table_size (socket_io_data.sock_to_state));
740 g_print ("-------------\n");
744 signal_handler (int signo)
749 g_print ("\n-----Non-IO-----\n");
750 print_pool_info (tp);
752 g_print ("\n-----IO-----\n");
753 print_pool_info (tp);
759 monitor_thread (gpointer unused)
761 ThreadPool *pools [2];
762 MonoInternalThread *thread;
767 pools [0] = &async_tp;
768 pools [1] = &async_io_tp;
769 thread = mono_thread_internal_current ();
770 ves_icall_System_Threading_Thread_SetName_internal (thread, mono_string_new (mono_domain_get (), "Threadpool monitor"));
773 i = 10; //number of spurious awakes we tolerate before doing a round of rebalancing.
776 ts = mono_msec_ticks ();
777 if (SleepEx (ms, TRUE) == 0)
779 ms -= (mono_msec_ticks () - ts);
780 if (mono_runtime_is_shutting_down ())
782 if (THREAD_WANTS_A_BREAK (thread))
783 mono_thread_interruption_checkpoint ();
784 } while (ms > 0 && i--);
786 if (mono_runtime_is_shutting_down ())
792 for (i = 0; i < 2; i++) {
797 need_one = (mono_cq_count (tp->queue) > 0);
798 if (!need_one && !tp->is_io) {
799 EnterCriticalSection (&wsqs_lock);
800 for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
802 wsq = g_ptr_array_index (wsqs, i);
803 if (mono_wsq_count (wsq) != 0) {
808 LeaveCriticalSection (&wsqs_lock);
811 threadpool_start_thread (tp);
817 mono_thread_pool_init_tls (void)
823 mono_thread_pool_init (void)
825 gint threads_per_cpu = 1;
827 gint cpu_count = mono_cpu_count ();
833 result = InterlockedCompareExchange (&tp_inited, 1, 0);
842 MONO_GC_REGISTER_ROOT_FIXED (socket_io_data.sock_to_state);
843 InitializeCriticalSection (&socket_io_data.io_lock);
844 if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
845 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
846 if (threads_per_cpu < 1)
850 thread_count = MIN (cpu_count * threads_per_cpu, 100 * cpu_count);
851 threadpool_init (&async_tp, thread_count, MAX (100 * cpu_count, thread_count), async_invoke_thread);
852 threadpool_init (&async_io_tp, cpu_count * 2, cpu_count * 4, async_invoke_thread);
853 async_io_tp.is_io = TRUE;
855 async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
856 g_assert (async_call_klass);
858 InitializeCriticalSection (&wsqs_lock);
859 wsqs = g_ptr_array_sized_new (MAX (100 * cpu_count, thread_count));
861 #ifndef DISABLE_PERFCOUNTERS
862 async_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "Work Items Added");
863 g_assert (async_tp.pc_nitems);
865 async_io_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "IO Work Items Added");
866 g_assert (async_io_tp.pc_nitems);
868 async_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of Threads");
869 g_assert (async_tp.pc_nthreads);
871 async_io_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of IO Threads");
872 g_assert (async_io_tp.pc_nthreads);
876 signal (SIGALRM, signal_handler);
881 static MonoAsyncResult *
882 create_simple_asyncresult (MonoObject *target, MonoObject *state)
884 MonoDomain *domain = mono_domain_get ();
885 MonoAsyncResult *ares;
887 /* Don't call mono_async_result_new() to avoid capturing the context */
888 ares = (MonoAsyncResult *) mono_object_new (domain, mono_defaults.asyncresult_class);
889 MONO_OBJECT_SETREF (ares, async_delegate, target);
890 MONO_OBJECT_SETREF (ares, async_state, state);
895 icall_append_io_job (MonoObject *target, MonoSocketAsyncResult *state)
897 MonoAsyncResult *ares;
899 ares = create_simple_asyncresult (target, (MonoObject *) state);
900 socket_io_add (ares, state);
904 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
907 MonoDomain *domain = mono_domain_get ();
908 MonoAsyncResult *ares;
911 ac = (ASyncCall*)mono_object_new (domain, async_call_klass);
912 MONO_OBJECT_SETREF (ac, msg, msg);
913 MONO_OBJECT_SETREF (ac, state, state);
915 if (async_callback) {
916 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
917 MONO_OBJECT_SETREF (ac, cb_target, async_callback);
920 ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
921 MONO_OBJECT_SETREF (ares, async_delegate, target);
923 #ifndef DISABLE_SOCKETS
924 if (socket_io_filter (target, state)) {
925 socket_io_add (ares, (MonoSocketAsyncResult *) state);
929 threadpool_append_job (&async_tp, (MonoObject *) ares);
934 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
942 /* check if already finished */
943 mono_monitor_enter ((MonoObject *) ares);
945 if (ares->endinvoke_called) {
946 *exc = (MonoObject *) mono_get_exception_invalid_operation (NULL);
947 mono_monitor_exit ((MonoObject *) ares);
951 ares->endinvoke_called = 1;
952 /* wait until we are really finished */
953 if (!ares->completed) {
954 if (ares->handle == NULL) {
955 wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
956 g_assert(wait_event != 0);
957 MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), wait_event));
959 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
961 mono_monitor_exit ((MonoObject *) ares);
962 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
964 mono_monitor_exit ((MonoObject *) ares);
967 ac = (ASyncCall *) ares->object_data;
968 g_assert (ac != NULL);
969 *exc = ac->msg->exc; /* FIXME: GC add write barrier */
970 *out_args = ac->out_args;
976 threadpool_kill_idle_threads (ThreadPool *tp)
980 n = (gint) InterlockedCompareExchange (&tp->max_threads, 0, -1);
983 MONO_SEM_POST (&tp->new_job);
988 mono_thread_pool_cleanup (void)
990 if (InterlockedExchange (&async_io_tp.pool_status, 2) == 1) {
991 socket_io_cleanup (&socket_io_data); /* Empty when DISABLE_SOCKETS is defined */
992 threadpool_kill_idle_threads (&async_io_tp);
995 if (async_io_tp.queue != NULL) {
996 MONO_SEM_DESTROY (&async_io_tp.new_job);
997 threadpool_free_queue (&async_io_tp);
1001 if (InterlockedExchange (&async_tp.pool_status, 2) == 1) {
1002 threadpool_kill_idle_threads (&async_tp);
1003 threadpool_free_queue (&async_tp);
1007 EnterCriticalSection (&wsqs_lock);
1008 mono_wsq_cleanup ();
1010 g_ptr_array_free (wsqs, TRUE);
1012 LeaveCriticalSection (&wsqs_lock);
1013 MONO_SEM_DESTROY (&async_tp.new_job);
1018 threadpool_start_thread (ThreadPool *tp)
1023 stack_size = (!tp->is_io) ? 0 : SMALL_STACK;
1024 while (!mono_runtime_is_shutting_down () && (n = tp->nthreads) < tp->max_threads) {
1025 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n) {
1026 #ifndef DISABLE_PERFCOUNTERS
1027 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
1029 mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE, FALSE, stack_size);
1038 pulse_on_new_job (ThreadPool *tp)
1041 MONO_SEM_POST (&tp->new_job);
1045 icall_append_job (MonoObject *ar)
1047 threadpool_append_jobs (&async_tp, &ar, 1);
1051 threadpool_append_job (ThreadPool *tp, MonoObject *ar)
1053 threadpool_append_jobs (tp, &ar, 1);
1057 threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs)
1059 static int job_counter;
1063 if (mono_runtime_is_shutting_down ())
1066 if (tp->pool_status == 0 && InterlockedCompareExchange (&tp->pool_status, 1, 0) == 0) {
1068 mono_thread_create_internal (mono_get_root_domain (), monitor_thread, NULL, TRUE, FALSE, SMALL_STACK);
1069 threadpool_start_thread (tp);
1071 /* Create on demand up to min_threads to avoid startup penalty for apps that don't use
1072 * the threadpool that much
1073 * mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, tp, TRUE, FALSE, SMALL_STACK);
1077 for (i = 0; i < njobs; i++) {
1079 if (ar == NULL || mono_domain_is_unloading (ar->vtable->domain))
1080 continue; /* Might happen when cleaning domain jobs */
1081 if (!tp->is_io && (InterlockedIncrement (&job_counter) % 10) == 0) {
1082 MonoAsyncResult *o = (MonoAsyncResult *) ar;
1083 o->add_time = mono_100ns_ticks ();
1085 threadpool_jobs_inc (ar);
1086 #ifndef DISABLE_PERFCOUNTERS
1087 mono_perfcounter_update_value (tp->pc_nitems, TRUE, 1);
1089 if (!tp->is_io && mono_wsq_local_push (ar))
1092 mono_cq_enqueue (tp->queue, ar);
1095 for (i = 0; tp->waiting > 0 && i < MIN(njobs, tp->max_threads); i++)
1096 pulse_on_new_job (tp);
1100 threadpool_clear_queue (ThreadPool *tp, MonoDomain *domain)
1103 MonoMList *other = NULL;
1104 MonoCQ *queue = tp->queue;
1109 while (mono_cq_dequeue (queue, &obj)) {
1112 if (obj->vtable->domain != domain)
1113 other = mono_mlist_prepend (other, obj);
1114 threadpool_jobs_dec (obj);
1117 if (mono_runtime_is_shutting_down ())
1121 threadpool_append_job (tp, (MonoObject *) mono_mlist_get_data (other));
1122 other = mono_mlist_next (other);
1127 remove_sockstate_for_domain (gpointer key, gpointer value, gpointer user_data)
1129 MonoMList *list = value;
1130 gboolean remove = FALSE;
1132 MonoObject *data = mono_mlist_get_data (list);
1133 if (mono_object_domain (data) == user_data) {
1135 mono_mlist_set_data (list, NULL);
1137 list = mono_mlist_next (list);
1139 //FIXME is there some sort of additional unregistration we need to perform here?
1144 * Clean up the threadpool of all domain jobs.
1145 * Can only be called as part of the domain unloading process as
1146 * it will wait for all jobs to be visible to the interruption code.
1149 mono_thread_pool_remove_domain_jobs (MonoDomain *domain, int timeout)
1153 guint32 start_time = 0;
1155 g_assert (domain->state == MONO_APPDOMAIN_UNLOADING);
1157 threadpool_clear_queue (&async_tp, domain);
1158 threadpool_clear_queue (&async_io_tp, domain);
1160 EnterCriticalSection (&socket_io_data.io_lock);
1161 if (socket_io_data.sock_to_state)
1162 mono_g_hash_table_foreach_remove (socket_io_data.sock_to_state, remove_sockstate_for_domain, domain);
1164 LeaveCriticalSection (&socket_io_data.io_lock);
1167 * There might be some threads out that could be about to execute stuff from the given domain.
1168 * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
1170 sem_handle = CreateSemaphore (NULL, 0, 1, NULL);
1172 domain->cleanup_semaphore = sem_handle;
1174 * The memory barrier here is required to have global ordering between assigning to cleanup_semaphone
1175 * and reading threadpool_jobs.
1176 * Otherwise this thread could read a stale version of threadpool_jobs and wait forever.
1178 mono_memory_write_barrier ();
1180 if (domain->threadpool_jobs && timeout != -1)
1181 start_time = mono_msec_ticks ();
1182 while (domain->threadpool_jobs) {
1183 WaitForSingleObject (sem_handle, timeout);
1184 if (timeout != -1 && (mono_msec_ticks () - start_time) > timeout) {
1190 domain->cleanup_semaphore = NULL;
1191 CloseHandle (sem_handle);
1196 threadpool_free_queue (ThreadPool *tp)
1198 mono_cq_destroy (tp->queue);
1203 mono_thread_pool_is_queue_array (MonoArray *o)
1205 // gpointer obj = o;
1207 // FIXME: need some fix in sgen code.
1217 EnterCriticalSection (&wsqs_lock);
1218 wsq = mono_wsq_create ();
1220 LeaveCriticalSection (&wsqs_lock);
1223 for (i = 0; i < wsqs->len; i++) {
1224 if (g_ptr_array_index (wsqs, i) == NULL) {
1225 wsqs->pdata [i] = wsq;
1226 LeaveCriticalSection (&wsqs_lock);
1230 g_ptr_array_add (wsqs, wsq);
1231 LeaveCriticalSection (&wsqs_lock);
1236 remove_wsq (MonoWSQ *wsq)
1243 EnterCriticalSection (&wsqs_lock);
1245 LeaveCriticalSection (&wsqs_lock);
1248 g_ptr_array_remove_fast (wsqs, wsq);
1251 * Only clean this up when shutting down, any other case will error out
1252 * if we're removing a queue that still has work items.
1254 if (mono_runtime_is_shutting_down ()) {
1255 while (mono_wsq_local_pop (&data)) {
1256 threadpool_jobs_dec (data);
1260 mono_wsq_destroy (wsq);
1261 LeaveCriticalSection (&wsqs_lock);
1265 try_steal (MonoWSQ *local_wsq, gpointer *data, gboolean retry)
1270 if (wsqs == NULL || data == NULL || *data != NULL)
1275 if (mono_runtime_is_shutting_down ())
1278 EnterCriticalSection (&wsqs_lock);
1279 for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
1282 wsq = wsqs->pdata [i];
1283 if (wsq == local_wsq || mono_wsq_count (wsq) == 0)
1285 mono_wsq_try_steal (wsqs->pdata [i], data, ms);
1286 if (*data != NULL) {
1287 LeaveCriticalSection (&wsqs_lock);
1291 LeaveCriticalSection (&wsqs_lock);
1293 } while (retry && ms < 11);
1297 dequeue_or_steal (ThreadPool *tp, gpointer *data, MonoWSQ *local_wsq)
1299 if (mono_runtime_is_shutting_down ())
1301 mono_cq_dequeue (tp->queue, (MonoObject **) data);
1302 if (!tp->is_io && !*data)
1303 try_steal (local_wsq, data, FALSE);
1304 return (*data != NULL);
1308 process_idle_times (ThreadPool *tp, gint64 t)
1312 gboolean compute_avg;
1316 if (tp->ignore_times || t <= 0)
1319 compute_avg = FALSE;
1320 ticks = mono_100ns_ticks ();
1322 SPIN_LOCK (tp->sp_lock);
1323 if (tp->ignore_times) {
1324 SPIN_UNLOCK (tp->sp_lock);
1329 if (tp->last_check == 0)
1330 tp->last_check = ticks;
1331 else if (tp->last_check > 0 && (ticks - tp->last_check) > 5000000) {
1332 tp->ignore_times = 1;
1335 SPIN_UNLOCK (tp->sp_lock);
1340 //printf ("Items: %d Time elapsed: %.3fs\n", tp->n_sum, (ticks - tp->last_check) / 10000.0);
1341 tp->last_check = ticks;
1343 avg = tp->time_sum / tp->n_sum;
1344 if (tp->averages [1] == 0) {
1345 tp->averages [1] = avg;
1347 per1 = ((100 * (ABS (avg - tp->averages [1]))) / tp->averages [1]);
1349 if (avg > tp->averages [1]) {
1350 if (tp->averages [1] < tp->averages [0]) {
1355 } else if (avg < tp->averages [1] && tp->averages [1] < tp->averages [0]) {
1360 min = tp->min_threads;
1362 if ((n - min) < min && tp->busy_threads == n)
1366 if (new_threads != 0) {
1367 printf ("n: %d per1: %lld avg=%lld avg1=%lld avg0=%lld\n", new_threads, per1, avg, tp->averages [1], tp->averages [0]);
1375 tp->averages [0] = tp->averages [1];
1376 tp->averages [1] = avg;
1377 tp->ignore_times = 0;
1379 if (new_threads == -1) {
1380 if (tp->destroy_thread == 0 && InterlockedCompareExchange (&tp->destroy_thread, 1, 0) == 0)
1381 pulse_on_new_job (tp);
1386 should_i_die (ThreadPool *tp)
1388 gboolean result = FALSE;
1389 if (tp->destroy_thread == 1 && InterlockedCompareExchange (&tp->destroy_thread, 0, 1) == 1)
1390 result = (tp->nthreads > tp->min_threads);
1395 async_invoke_thread (gpointer data)
1398 MonoInternalThread *thread;
1409 thread = mono_thread_internal_current ();
1411 mono_profiler_thread_start (thread->tid);
1412 name = (tp->is_io) ? "IO Threadpool worker" : "Threadpool worker";
1413 mono_thread_set_name_internal (thread, mono_string_new (mono_domain_get (), name), FALSE);
1416 tp_start_func (tp_hooks_user_data);
1420 MonoAsyncResult *ar;
1422 gboolean is_io_task;
1427 ar = (MonoAsyncResult *) data;
1429 InterlockedIncrement (&tp->busy_threads);
1430 domain = ((MonoObject *)ar)->vtable->domain;
1431 #ifndef DISABLE_SOCKETS
1432 klass = ((MonoObject *) data)->vtable->klass;
1433 is_io_task = !is_corlib_asyncresult (domain, klass);
1436 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1437 is_socket = is_socketasyncresult (domain, klass);
1439 switch (state->operation) {
1440 case AIO_OP_RECEIVE:
1441 state->total = ICALL_RECV (state);
1444 state->total = ICALL_SEND (state);
1449 /* worker threads invokes methods in different domains,
1450 * so we need to set the right domain here */
1453 if (mono_domain_is_unloading (domain) || mono_runtime_is_shutting_down ()) {
1454 threadpool_jobs_dec ((MonoObject *)ar);
1457 InterlockedDecrement (&tp->busy_threads);
1459 mono_thread_push_appdomain_ref (domain);
1460 if (threadpool_jobs_dec ((MonoObject *)ar)) {
1463 mono_thread_pop_appdomain_ref ();
1464 InterlockedDecrement (&tp->busy_threads);
1468 if (mono_domain_set (domain, FALSE)) {
1471 if (tp_item_begin_func)
1472 tp_item_begin_func (tp_item_user_data);
1474 if (!is_io_task && ar->add_time > 0)
1475 process_idle_times (tp, ar->add_time);
1476 exc = mono_async_invoke (tp, ar);
1477 if (tp_item_end_func)
1478 tp_item_end_func (tp_item_user_data);
1480 mono_internal_thread_unhandled_exception (exc);
1481 if (is_socket && tp->is_io) {
1482 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1484 if (state->completed && state->callback) {
1485 MonoAsyncResult *cb_ares;
1486 cb_ares = create_simple_asyncresult ((MonoObject *) state->callback,
1487 (MonoObject *) state);
1488 icall_append_job ((MonoObject *) cb_ares);
1491 mono_domain_set (mono_get_root_domain (), TRUE);
1493 mono_thread_pop_appdomain_ref ();
1494 InterlockedDecrement (&tp->busy_threads);
1495 /* If the callee changes the background status, set it back to TRUE */
1496 mono_thread_clr_state (thread , ~ThreadState_Background);
1497 if (!mono_thread_test_state (thread , ThreadState_Background))
1498 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
1504 must_die = should_i_die (tp);
1505 if (!must_die && (tp->is_io || !mono_wsq_local_pop (&data)))
1506 dequeue_or_steal (tp, &data, wsq);
1509 while (!must_die && !data && n_naps < 4) {
1512 InterlockedIncrement (&tp->waiting);
1514 // Another thread may have added a job into its wsq since the last call to dequeue_or_steal
1515 // Check all the queues again before entering the wait loop
1516 dequeue_or_steal (tp, &data, wsq);
1518 InterlockedDecrement (&tp->waiting);
1522 mono_gc_set_skip_thread (TRUE);
1524 #if defined(__OpenBSD__)
1525 while (mono_cq_count (tp->queue) == 0 && (res = mono_sem_wait (&tp->new_job, TRUE)) == -1) {// && errno == EINTR) {
1527 while (mono_cq_count (tp->queue) == 0 && (res = mono_sem_timedwait (&tp->new_job, 2000, TRUE)) == -1) {// && errno == EINTR) {
1529 if (mono_runtime_is_shutting_down ())
1531 if (THREAD_WANTS_A_BREAK (thread))
1532 mono_thread_interruption_checkpoint ();
1534 InterlockedDecrement (&tp->waiting);
1536 mono_gc_set_skip_thread (FALSE);
1538 if (mono_runtime_is_shutting_down ())
1540 must_die = should_i_die (tp);
1541 dequeue_or_steal (tp, &data, wsq);
1545 if (!data && !tp->is_io && !mono_runtime_is_shutting_down ()) {
1546 mono_wsq_local_pop (&data);
1547 if (data && must_die) {
1548 InterlockedCompareExchange (&tp->destroy_thread, 1, 0);
1549 pulse_on_new_job (tp);
1558 down = mono_runtime_is_shutting_down ();
1559 if (!down && nt <= tp->min_threads)
1561 if (down || InterlockedCompareExchange (&tp->nthreads, nt - 1, nt) == nt) {
1562 #ifndef DISABLE_PERFCOUNTERS
1563 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, -1);
1569 mono_profiler_thread_end (thread->tid);
1572 tp_finish_func (tp_hooks_user_data);
1579 g_assert_not_reached ();
1583 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
1585 *workerThreads = async_tp.max_threads - async_tp.busy_threads;
1586 *completionPortThreads = async_io_tp.max_threads - async_io_tp.busy_threads;
1590 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
1592 *workerThreads = async_tp.max_threads;
1593 *completionPortThreads = async_io_tp.max_threads;
1597 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
1599 *workerThreads = async_tp.min_threads;
1600 *completionPortThreads = async_io_tp.min_threads;
1604 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
1607 gint max_io_threads;
1609 max_threads = async_tp.max_threads;
1610 if (workerThreads <= 0 || workerThreads > max_threads)
1613 max_io_threads = async_io_tp.max_threads;
1614 if (completionPortThreads <= 0 || completionPortThreads > max_io_threads)
1617 InterlockedExchange (&async_tp.min_threads, workerThreads);
1618 InterlockedExchange (&async_io_tp.min_threads, completionPortThreads);
1619 if (workerThreads > async_tp.nthreads)
1620 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_tp, TRUE, FALSE, SMALL_STACK);
1621 if (completionPortThreads > async_io_tp.nthreads)
1622 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_io_tp, TRUE, FALSE, SMALL_STACK);
1627 ves_icall_System_Threading_ThreadPool_SetMaxThreads (gint workerThreads, gint completionPortThreads)
1630 gint min_io_threads;
1633 cpu_count = mono_cpu_count ();
1634 min_threads = async_tp.min_threads;
1635 if (workerThreads < min_threads || workerThreads < cpu_count)
1638 /* We don't really have the concept of completion ports. Do we care here? */
1639 min_io_threads = async_io_tp.min_threads;
1640 if (completionPortThreads < min_io_threads || completionPortThreads < cpu_count)
1643 InterlockedExchange (&async_tp.max_threads, workerThreads);
1644 InterlockedExchange (&async_io_tp.max_threads, completionPortThreads);
1649 * mono_install_threadpool_thread_hooks
1650 * @start_func: the function to be called right after a new threadpool thread is created. Can be NULL.
1651 * @finish_func: the function to be called right before a thredpool thread is exiting. Can be NULL.
1652 * @user_data: argument passed to @start_func and @finish_func.
1654 * @start_fun will be called right after a threadpool thread is created and @finish_func right before a threadpool thread exits.
1655 * The calls will be made from the thread itself.
1658 mono_install_threadpool_thread_hooks (MonoThreadPoolFunc start_func, MonoThreadPoolFunc finish_func, gpointer user_data)
1660 tp_start_func = start_func;
1661 tp_finish_func = finish_func;
1662 tp_hooks_user_data = user_data;
1666 * mono_install_threadpool_item_hooks
1667 * @begin_func: the function to be called before a threadpool work item processing starts.
1668 * @end_func: the function to be called after a threadpool work item is finished.
1669 * @user_data: argument passed to @begin_func and @end_func.
1671 * The calls will be made from the thread itself and from the same AppDomain
1672 * where the work item was executed.
1676 mono_install_threadpool_item_hooks (MonoThreadPoolItemFunc begin_func, MonoThreadPoolItemFunc end_func, gpointer user_data)
1678 tp_item_begin_func = begin_func;
1679 tp_item_end_func = end_func;
1680 tp_item_user_data = user_data;
1684 mono_internal_thread_unhandled_exception (MonoObject* exc)
1686 if (mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_CURRENT) {
1690 klass = exc->vtable->klass;
1691 unloaded = is_appdomainunloaded_exception (exc->vtable->domain, klass);
1692 if (!unloaded && klass != mono_defaults.threadabortexception_class) {
1693 mono_unhandled_exception (exc);
1694 if (mono_environment_exitcode_get () == 1)
1697 if (klass == mono_defaults.threadabortexception_class)
1698 mono_thread_internal_reset_abort (mono_thread_internal_current ());
1703 * Suspend creation of new threads.
1706 mono_thread_pool_suspend (void)
1712 * Resume creation of new threads.
1715 mono_thread_pool_resume (void)