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>
33 #ifdef HAVE_SYS_TIME_H
36 #include <sys/types.h>
42 #ifdef HAVE_SYS_SOCKET_H
43 #include <sys/socket.h>
45 #include <mono/utils/mono-poll.h>
47 #include <sys/epoll.h>
50 #include <sys/event.h>
54 #ifndef DISABLE_SOCKETS
55 #include "mono/io-layer/socket-wrappers.h"
58 #include "threadpool.h"
60 #define THREAD_WANTS_A_BREAK(t) ((t->state & (ThreadState_StopRequested | \
61 ThreadState_SuspendRequested)) != 0)
63 #define SPIN_TRYLOCK(i) (InterlockedCompareExchange (&(i), 1, 0) == 0)
64 #define SPIN_LOCK(i) do { \
65 if (SPIN_TRYLOCK (i)) \
69 #define SPIN_UNLOCK(i) i = 0
70 #define SMALL_STACK (128 * (sizeof (gpointer) / 4) * 1024)
72 /* DEBUG: prints tp data every 2s */
75 /* mono_thread_pool_init called */
76 static volatile int tp_inited;
85 CRITICAL_SECTION io_lock; /* access to sock_to_state */
86 int inited; // 0 -> not initialized , 1->initializing, 2->initialized, 3->cleaned up
87 MonoGHashTable *sock_to_state;
91 void (*modify) (gpointer event_data, int fd, int operation, int events, gboolean is_new);
92 void (*wait) (gpointer sock_data);
93 void (*shutdown) (gpointer event_data);
96 static SocketIOData socket_io_data;
98 /* Keep in sync with the System.MonoAsyncCall class which provides GC tracking */
101 MonoMethodMessage *msg;
102 MonoMethod *cb_method;
103 MonoDelegate *cb_target;
111 MonoCQ *queue; /* GC root */
113 volatile gint waiting; /* threads waiting for a work item */
116 volatile gint pool_status; /* 0 -> not initialized, 1 -> initialized, 2 -> cleaning up */
117 /* min, max, n and busy -> Interlocked */
118 volatile gint min_threads;
119 volatile gint max_threads;
120 volatile gint nthreads;
121 volatile gint busy_threads;
123 void (*async_invoke) (gpointer data);
124 void *pc_nitems; /* Performance counter for total number of items in added */
125 void *pc_nthreads; /* Performance counter for total number of active threads */
127 volatile gint destroy_thread;
128 volatile gint ignore_times; /* Used when there's a thread being created or destroyed */
129 volatile gint sp_lock; /* spin lock used to protect ignore_times */
130 volatile gint64 last_check;
131 volatile gint64 time_sum;
137 static ThreadPool async_tp;
138 static ThreadPool async_io_tp;
140 static void async_invoke_thread (gpointer data);
141 static MonoObject *mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares);
142 static void threadpool_free_queue (ThreadPool *tp);
143 static void threadpool_append_job (ThreadPool *tp, MonoObject *ar);
144 static void threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs);
145 static void threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer));
146 static void threadpool_start_idle_threads (ThreadPool *tp);
147 static void threadpool_kill_idle_threads (ThreadPool *tp);
148 static gboolean threadpool_start_thread (ThreadPool *tp);
149 static void monitor_thread (gpointer data);
150 static void socket_io_cleanup (SocketIOData *data);
151 static MonoObject *get_io_event (MonoMList **list, gint event);
152 static int get_events_from_list (MonoMList *list);
153 static int get_event_from_state (MonoSocketAsyncResult *state);
155 static MonoClass *async_call_klass;
156 static MonoClass *socket_async_call_klass;
157 static MonoClass *process_async_call_klass;
159 static GPtrArray *wsqs;
160 CRITICAL_SECTION wsqs_lock;
163 static MonoThreadPoolFunc tp_start_func;
164 static MonoThreadPoolFunc tp_finish_func;
165 static gpointer tp_hooks_user_data;
166 static MonoThreadPoolItemFunc tp_item_begin_func;
167 static MonoThreadPoolItemFunc tp_item_end_func;
168 static gpointer tp_item_user_data;
178 AIO_OP_RECV_JUST_CALLBACK,
179 AIO_OP_SEND_JUST_CALLBACK,
183 AIO_OP_ACCEPTRECEIVE,
184 AIO_OP_RECEIVE_BUFFERS,
189 #include <mono/metadata/tpool-poll.c>
191 #include <mono/metadata/tpool-epoll.c>
192 #elif defined(HAVE_KQUEUE)
193 #include <mono/metadata/tpool-kqueue.c>
196 * Functions to check whenever a class is given system class. We need to cache things in MonoDomain since some of the
197 * assemblies can be unloaded.
201 is_system_type (MonoDomain *domain, MonoClass *klass)
203 if (domain->system_image == NULL)
204 domain->system_image = mono_image_loaded ("System");
206 return klass->image == domain->system_image;
210 is_corlib_type (MonoDomain *domain, MonoClass *klass)
212 return klass->image == mono_defaults.corlib;
216 * Note that we call it is_socket_type() where 'socket' refers to the image
217 * that contains the System.Net.Sockets.Socket type.
218 * For moonlight there is a System.Net.Sockets.Socket class in both System.dll and System.Net.dll.
221 is_socket_type (MonoDomain *domain, MonoClass *klass)
223 static const char *version = NULL;
224 static gboolean moonlight;
226 if (is_system_type (domain, klass))
229 /* If moonlight, check if the type is in System.Net.dll too */
230 if (version == NULL) {
231 version = mono_get_runtime_info ()->framework_version;
232 moonlight = !strcmp (version, "2.1");
238 if (domain->system_net_dll == NULL)
239 domain->system_net_dll = mono_image_loaded ("System.Net");
241 return klass->image == domain->system_net_dll;
244 #define check_type_cached(domain, ASSEMBLY, _class, _namespace, _name, loc) do { \
246 return *loc == _class; \
247 if (is_##ASSEMBLY##_type (domain, _class) && !strcmp (_name, _class->name) && !strcmp (_namespace, _class->name_space)) { \
254 #define check_corlib_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, corlib, _class, _namespace, _name, loc)
256 #define check_socket_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, socket, _class, _namespace, _name, loc)
258 #define check_system_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, system, _class, _namespace, _name, loc)
261 is_corlib_asyncresult (MonoDomain *domain, MonoClass *klass)
263 check_corlib_type_cached (domain, klass, "System.Runtime.Remoting.Messaging", "AsyncResult", &domain->corlib_asyncresult_class);
267 is_socket (MonoDomain *domain, MonoClass *klass)
269 check_socket_type_cached (domain, klass, "System.Net.Sockets", "Socket", &domain->socket_class);
273 is_socketasyncresult (MonoDomain *domain, MonoClass *klass)
275 return (klass->nested_in &&
276 is_socket (domain, klass->nested_in) &&
277 !strcmp (klass->name, "SocketAsyncResult"));
281 is_socketasynccall (MonoDomain *domain, MonoClass *klass)
283 return (klass->nested_in &&
284 is_socket (domain, klass->nested_in) &&
285 !strcmp (klass->name, "SocketAsyncCall"));
289 is_appdomainunloaded_exception (MonoDomain *domain, MonoClass *klass)
291 check_corlib_type_cached (domain, klass, "System", "AppDomainUnloadedException", &domain->ad_unloaded_ex_class);
295 is_sd_process (MonoDomain *domain, MonoClass *klass)
297 check_system_type_cached (domain, klass, "System.Diagnostics", "Process", &domain->process_class);
301 is_sdp_asyncreadhandler (MonoDomain *domain, MonoClass *klass)
304 return (klass->nested_in &&
305 is_sd_process (domain, klass->nested_in) &&
306 !strcmp (klass->name, "AsyncReadHandler"));
310 #ifdef DISABLE_SOCKETS
312 #define socket_io_cleanup(x)
315 get_event_from_state (MonoSocketAsyncResult *state)
317 g_assert_not_reached ();
322 get_events_from_list (MonoMList *list)
330 socket_io_cleanup (SocketIOData *data)
332 EnterCriticalSection (&data->io_lock);
333 if (data->inited != 2) {
334 LeaveCriticalSection (&data->io_lock);
338 data->shutdown (data->event_data);
339 LeaveCriticalSection (&data->io_lock);
343 get_event_from_state (MonoSocketAsyncResult *state)
345 switch (state->operation) {
348 case AIO_OP_RECV_JUST_CALLBACK:
349 case AIO_OP_RECEIVEFROM:
350 case AIO_OP_READPIPE:
351 case AIO_OP_ACCEPTRECEIVE:
352 case AIO_OP_RECEIVE_BUFFERS:
355 case AIO_OP_SEND_JUST_CALLBACK:
358 case AIO_OP_SEND_BUFFERS:
359 case AIO_OP_DISCONNECT:
361 default: /* Should never happen */
362 g_message ("get_event_from_state: unknown value in switch!!!");
368 get_events_from_list (MonoMList *list)
370 MonoSocketAsyncResult *state;
373 while (list && (state = (MonoSocketAsyncResult *)mono_mlist_get_data (list))) {
374 events |= get_event_from_state (state);
375 list = mono_mlist_next (list);
381 #define ICALL_RECV(x) ves_icall_System_Net_Sockets_Socket_Receive_internal (\
382 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
383 x->socket_flags, &x->error);
385 #define ICALL_SEND(x) ves_icall_System_Net_Sockets_Socket_Send_internal (\
386 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
387 x->socket_flags, &x->error);
389 #endif /* !DISABLE_SOCKETS */
392 threadpool_jobs_inc (MonoObject *obj)
395 InterlockedIncrement (&obj->vtable->domain->threadpool_jobs);
399 threadpool_jobs_dec (MonoObject *obj)
401 MonoDomain *domain = obj->vtable->domain;
402 int remaining_jobs = InterlockedDecrement (&domain->threadpool_jobs);
403 if (remaining_jobs == 0 && domain->cleanup_semaphore) {
404 ReleaseSemaphore (domain->cleanup_semaphore, 1, NULL);
411 get_io_event (MonoMList **list, gint event)
421 state = mono_mlist_get_data (current);
422 if (get_event_from_state ((MonoSocketAsyncResult *) state) == event)
427 current = mono_mlist_next (current);
432 mono_mlist_set_next (prev, mono_mlist_next (current));
434 *list = mono_mlist_next (*list);
442 * select/poll wake up when a socket is closed, but epoll just removes
443 * the socket from its internal list without notification.
446 mono_thread_pool_remove_socket (int sock)
449 MonoSocketAsyncResult *state;
452 if (socket_io_data.inited == 0)
455 EnterCriticalSection (&socket_io_data.io_lock);
456 if (socket_io_data.sock_to_state == NULL) {
457 LeaveCriticalSection (&socket_io_data.io_lock);
460 list = mono_g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
462 mono_g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
463 LeaveCriticalSection (&socket_io_data.io_lock);
466 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
467 if (state->operation == AIO_OP_RECEIVE)
468 state->operation = AIO_OP_RECV_JUST_CALLBACK;
469 else if (state->operation == AIO_OP_SEND)
470 state->operation = AIO_OP_SEND_JUST_CALLBACK;
472 ares = get_io_event (&list, MONO_POLLIN);
473 threadpool_append_job (&async_io_tp, ares);
475 ares = get_io_event (&list, MONO_POLLOUT);
476 threadpool_append_job (&async_io_tp, ares);
482 init_event_system (SocketIOData *data)
485 if (data->event_system == EPOLL_BACKEND) {
486 data->event_data = tp_epoll_init (data);
487 if (data->event_data == NULL) {
488 if (g_getenv ("MONO_DEBUG"))
489 g_message ("Falling back to poll()");
490 data->event_system = POLL_BACKEND;
493 #elif defined(HAVE_KQUEUE)
494 if (data->event_system == KQUEUE_BACKEND)
495 data->event_data = tp_kqueue_init (data);
497 if (data->event_system == POLL_BACKEND)
498 data->event_data = tp_poll_init (data);
502 socket_io_init (SocketIOData *data)
506 if (data->inited >= 2) // 2 -> initialized, 3-> cleaned up
509 inited = InterlockedCompareExchange (&data->inited, 1, 0);
512 if (data->inited >= 2)
518 EnterCriticalSection (&data->io_lock);
519 data->sock_to_state = mono_g_hash_table_new_type (g_direct_hash, g_direct_equal, MONO_HASH_VALUE_GC);
521 data->event_system = EPOLL_BACKEND;
522 #elif defined(HAVE_KQUEUE)
523 data->event_system = KQUEUE_BACKEND;
525 data->event_system = POLL_BACKEND;
527 if (g_getenv ("MONO_DISABLE_AIO") != NULL)
528 data->event_system = POLL_BACKEND;
530 init_event_system (data);
531 mono_thread_create_internal (mono_get_root_domain (), data->wait, data, TRUE, SMALL_STACK);
532 LeaveCriticalSection (&data->io_lock);
534 threadpool_start_thread (&async_io_tp);
538 socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
541 SocketIOData *data = &socket_io_data;
546 socket_io_init (&socket_io_data);
547 if (mono_runtime_is_shutting_down () || data->inited == 3 || data->sock_to_state == NULL)
549 if (async_tp.pool_status == 2)
552 MONO_OBJECT_SETREF (state, ares, ares);
554 fd = GPOINTER_TO_INT (state->handle);
555 EnterCriticalSection (&data->io_lock);
556 if (data->sock_to_state == NULL) {
557 LeaveCriticalSection (&data->io_lock);
560 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
562 list = mono_mlist_alloc ((MonoObject*)state);
565 list = mono_mlist_append (list, (MonoObject*)state);
569 mono_g_hash_table_replace (data->sock_to_state, state->handle, list);
570 ievt = get_events_from_list (list);
571 LeaveCriticalSection (&data->io_lock);
572 data->modify (data->event_data, fd, state->operation, ievt, is_new);
575 #ifndef DISABLE_SOCKETS
577 socket_io_filter (MonoObject *target, MonoObject *state)
580 MonoSocketAsyncResult *sock_res;
584 if (target == NULL || state == NULL)
587 domain = target->vtable->domain;
588 klass = target->vtable->klass;
589 if (socket_async_call_klass == NULL && is_socketasynccall (domain, klass))
590 socket_async_call_klass = klass;
592 if (process_async_call_klass == NULL && is_sdp_asyncreadhandler (domain, klass))
593 process_async_call_klass = klass;
595 if (klass != socket_async_call_klass && klass != process_async_call_klass)
598 sock_res = (MonoSocketAsyncResult *) state;
599 op = sock_res->operation;
600 if (op < AIO_OP_FIRST || op >= AIO_OP_LAST)
605 #endif /* !DISABLE_SOCKETS */
607 /* Returns the exception thrown when invoking, if any */
609 mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares)
611 ASyncCall *ac = (ASyncCall *)ares->object_data;
612 MonoObject *res, *exc = NULL;
613 MonoArray *out_args = NULL;
614 HANDLE wait_event = NULL;
616 if (ares->execution_context) {
617 /* use captured ExecutionContext (if available) */
618 MONO_OBJECT_SETREF (ares, original_context, mono_thread_get_execution_context ());
619 mono_thread_set_execution_context (ares->execution_context);
621 ares->original_context = NULL;
625 /* Fast path from ThreadPool.*QueueUserWorkItem */
626 void *pa = ares->async_state;
627 mono_runtime_delegate_invoke (ares->async_delegate, &pa, &exc);
629 MonoObject *cb_exc = NULL;
632 res = mono_message_invoke (ares->async_delegate, ac->msg, &exc, &out_args);
633 MONO_OBJECT_SETREF (ac, res, res);
634 MONO_OBJECT_SETREF (ac, msg->exc, exc);
635 MONO_OBJECT_SETREF (ac, out_args, out_args);
637 mono_monitor_enter ((MonoObject *) ares);
639 if (ares->handle != NULL)
640 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
641 mono_monitor_exit ((MonoObject *) ares);
642 /* notify listeners */
643 if (wait_event != NULL)
644 SetEvent (wait_event);
646 /* call async callback if cb_method != null*/
647 if (ac != NULL && ac->cb_method) {
650 mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &cb_exc);
651 MONO_OBJECT_SETREF (ac->msg, exc, cb_exc);
658 /* restore original thread execution context if flow isn't suppressed, i.e. non null */
659 if (ares->original_context) {
660 mono_thread_set_execution_context (ares->original_context);
661 ares->original_context = NULL;
667 threadpool_start_idle_threads (ThreadPool *tp)
672 stack_size = (!tp->is_io) ? 0 : SMALL_STACK;
676 if (n >= tp->min_threads)
678 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n)
681 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
682 mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE, stack_size);
688 threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer))
690 memset (tp, 0, sizeof (ThreadPool));
691 tp->min_threads = min_threads;
692 tp->max_threads = max_threads;
693 tp->async_invoke = async_invoke;
694 tp->queue = mono_cq_create ();
695 MONO_SEM_INIT (&tp->new_job, 0);
699 init_perf_counter (const char *category, const char *counter)
701 MonoString *category_str;
702 MonoString *counter_str;
708 if (category == NULL || counter == NULL)
710 root = mono_get_root_domain ();
711 category_str = mono_string_new (root, category);
712 counter_str = mono_string_new (root, counter);
713 machine = mono_string_new (root, ".");
714 return mono_perfcounter_get_impl (category_str, counter_str, NULL, machine, &type, &custom);
719 print_pool_info (ThreadPool *tp)
722 // if (tp->tail - tp->head == 0)
725 g_print ("Pool status? %d\n", InterlockedCompareExchange (&tp->pool_status, 0, 0));
726 g_print ("Min. threads: %d\n", InterlockedCompareExchange (&tp->min_threads, 0, 0));
727 g_print ("Max. threads: %d\n", InterlockedCompareExchange (&tp->max_threads, 0, 0));
728 g_print ("nthreads: %d\n", InterlockedCompareExchange (&tp->nthreads, 0, 0));
729 g_print ("busy threads: %d\n", InterlockedCompareExchange (&tp->busy_threads, 0, 0));
730 g_print ("Waiting: %d\n", InterlockedCompareExchange (&tp->waiting, 0, 0));
731 g_print ("Queued: %d\n", (tp->tail - tp->head));
732 if (tp == &async_tp) {
734 EnterCriticalSection (&wsqs_lock);
735 for (i = 0; i < wsqs->len; i++) {
736 g_print ("\tWSQ %d: %d\n", i, mono_wsq_count (g_ptr_array_index (wsqs, i)));
738 LeaveCriticalSection (&wsqs_lock);
740 g_print ("\tSockets: %d\n", mono_g_hash_table_size (socket_io_data.sock_to_state));
742 g_print ("-------------\n");
746 signal_handler (int signo)
751 g_print ("\n-----Non-IO-----\n");
752 print_pool_info (tp);
754 g_print ("\n-----IO-----\n");
755 print_pool_info (tp);
761 monitor_thread (gpointer unused)
763 ThreadPool *pools [2];
764 MonoInternalThread *thread;
769 pools [0] = &async_tp;
770 pools [1] = &async_io_tp;
771 thread = mono_thread_internal_current ();
772 ves_icall_System_Threading_Thread_SetName_internal (thread, mono_string_new (mono_domain_get (), "Threadpool monitor"));
777 ts = mono_msec_ticks ();
778 if (SleepEx (ms, TRUE) == 0)
780 ms -= (mono_msec_ticks () - ts);
781 if (mono_runtime_is_shutting_down ())
783 if (THREAD_WANTS_A_BREAK (thread))
784 mono_thread_interruption_checkpoint ();
787 if (mono_runtime_is_shutting_down ())
790 for (i = 0; i < 2; i++) {
795 need_one = (mono_cq_count (tp->queue) > 0);
796 if (!need_one && !tp->is_io) {
797 EnterCriticalSection (&wsqs_lock);
798 for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
800 wsq = g_ptr_array_index (wsqs, i);
801 if (mono_wsq_count (wsq) != 0) {
806 LeaveCriticalSection (&wsqs_lock);
809 threadpool_start_thread (tp);
815 mono_thread_pool_init ()
817 gint threads_per_cpu = 1;
819 gint cpu_count = mono_cpu_count ();
825 result = InterlockedCompareExchange (&tp_inited, 1, 0);
834 MONO_GC_REGISTER_ROOT_FIXED (socket_io_data.sock_to_state);
835 InitializeCriticalSection (&socket_io_data.io_lock);
836 if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
837 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
838 if (threads_per_cpu < 1)
842 thread_count = MIN (cpu_count * threads_per_cpu, 100 * cpu_count);
843 threadpool_init (&async_tp, thread_count, MAX (100 * cpu_count, thread_count), async_invoke_thread);
844 threadpool_init (&async_io_tp, cpu_count * 2, cpu_count * 4, async_invoke_thread);
845 async_io_tp.is_io = TRUE;
847 async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
848 g_assert (async_call_klass);
850 InitializeCriticalSection (&wsqs_lock);
851 wsqs = g_ptr_array_sized_new (MAX (100 * cpu_count, thread_count));
854 async_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "Work Items Added");
855 g_assert (async_tp.pc_nitems);
857 async_io_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "IO Work Items Added");
858 g_assert (async_io_tp.pc_nitems);
860 async_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of Threads");
861 g_assert (async_tp.pc_nthreads);
863 async_io_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of IO Threads");
864 g_assert (async_io_tp.pc_nthreads);
867 signal (SIGALRM, signal_handler);
872 static MonoAsyncResult *
873 create_simple_asyncresult (MonoObject *target, MonoObject *state)
875 MonoDomain *domain = mono_domain_get ();
876 MonoAsyncResult *ares;
878 /* Don't call mono_async_result_new() to avoid capturing the context */
879 ares = (MonoAsyncResult *) mono_object_new (domain, mono_defaults.asyncresult_class);
880 MONO_OBJECT_SETREF (ares, async_delegate, target);
881 MONO_OBJECT_SETREF (ares, async_state, state);
886 icall_append_io_job (MonoObject *target, MonoSocketAsyncResult *state)
888 MonoAsyncResult *ares;
890 ares = create_simple_asyncresult (target, (MonoObject *) state);
891 socket_io_add (ares, state);
895 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
898 MonoDomain *domain = mono_domain_get ();
899 MonoAsyncResult *ares;
902 ac = (ASyncCall*)mono_object_new (domain, async_call_klass);
903 MONO_OBJECT_SETREF (ac, msg, msg);
904 MONO_OBJECT_SETREF (ac, state, state);
906 if (async_callback) {
907 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
908 MONO_OBJECT_SETREF (ac, cb_target, async_callback);
911 ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
912 MONO_OBJECT_SETREF (ares, async_delegate, target);
914 #ifndef DISABLE_SOCKETS
915 if (socket_io_filter (target, state)) {
916 socket_io_add (ares, (MonoSocketAsyncResult *) state);
920 threadpool_append_job (&async_tp, (MonoObject *) ares);
925 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
933 /* check if already finished */
934 mono_monitor_enter ((MonoObject *) ares);
936 if (ares->endinvoke_called) {
937 *exc = (MonoObject *) mono_get_exception_invalid_operation (NULL);
938 mono_monitor_exit ((MonoObject *) ares);
942 ares->endinvoke_called = 1;
943 /* wait until we are really finished */
944 if (!ares->completed) {
945 if (ares->handle == NULL) {
946 wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
947 g_assert(wait_event != 0);
948 MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), wait_event));
950 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
952 mono_monitor_exit ((MonoObject *) ares);
953 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
955 mono_monitor_exit ((MonoObject *) ares);
958 ac = (ASyncCall *) ares->object_data;
959 g_assert (ac != NULL);
960 *exc = ac->msg->exc; /* FIXME: GC add write barrier */
961 *out_args = ac->out_args;
967 threadpool_kill_idle_threads (ThreadPool *tp)
971 n = (gint) InterlockedCompareExchange (&tp->max_threads, 0, -1);
974 MONO_SEM_POST (&tp->new_job);
979 mono_thread_pool_cleanup (void)
981 if (InterlockedExchange (&async_io_tp.pool_status, 2) == 1) {
982 socket_io_cleanup (&socket_io_data); /* Empty when DISABLE_SOCKETS is defined */
983 threadpool_kill_idle_threads (&async_io_tp);
986 if (async_io_tp.queue != NULL) {
987 MONO_SEM_DESTROY (&async_io_tp.new_job);
988 threadpool_free_queue (&async_io_tp);
992 if (InterlockedExchange (&async_tp.pool_status, 2) == 1) {
993 threadpool_kill_idle_threads (&async_tp);
994 threadpool_free_queue (&async_tp);
998 EnterCriticalSection (&wsqs_lock);
1001 g_ptr_array_free (wsqs, TRUE);
1003 LeaveCriticalSection (&wsqs_lock);
1004 MONO_SEM_DESTROY (&async_tp.new_job);
1009 threadpool_start_thread (ThreadPool *tp)
1014 stack_size = (!tp->is_io) ? 0 : SMALL_STACK;
1015 while (!mono_runtime_is_shutting_down () && (n = tp->nthreads) < tp->max_threads) {
1016 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n) {
1017 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
1018 mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE, stack_size);
1027 pulse_on_new_job (ThreadPool *tp)
1030 MONO_SEM_POST (&tp->new_job);
1034 icall_append_job (MonoObject *ar)
1036 threadpool_append_jobs (&async_tp, &ar, 1);
1040 threadpool_append_job (ThreadPool *tp, MonoObject *ar)
1042 threadpool_append_jobs (tp, &ar, 1);
1046 threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs)
1048 static int job_counter;
1052 if (mono_runtime_is_shutting_down ())
1055 if (tp->pool_status == 0 && InterlockedCompareExchange (&tp->pool_status, 1, 0) == 0) {
1057 mono_thread_create_internal (mono_get_root_domain (), monitor_thread, NULL, TRUE, SMALL_STACK);
1058 threadpool_start_thread (tp);
1060 /* Create on demand up to min_threads to avoid startup penalty for apps that don't use
1061 * the threadpool that much
1062 * mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, tp, TRUE, SMALL_STACK);
1066 for (i = 0; i < njobs; i++) {
1068 if (ar == NULL || mono_domain_is_unloading (ar->vtable->domain))
1069 continue; /* Might happen when cleaning domain jobs */
1070 if (!tp->is_io && (InterlockedIncrement (&job_counter) % 10) == 0) {
1071 MonoAsyncResult *o = (MonoAsyncResult *) ar;
1072 o->add_time = mono_100ns_ticks ();
1074 threadpool_jobs_inc (ar);
1075 mono_perfcounter_update_value (tp->pc_nitems, TRUE, 1);
1076 if (!tp->is_io && mono_wsq_local_push (ar))
1079 mono_cq_enqueue (tp->queue, ar);
1082 for (i = 0; tp->waiting > 0 && i < MIN(njobs, tp->max_threads); i++)
1083 pulse_on_new_job (tp);
1087 threadpool_clear_queue (ThreadPool *tp, MonoDomain *domain)
1093 while (mono_cq_dequeue (tp->queue, &obj)) {
1096 if (obj->vtable->domain != domain)
1097 other = mono_mlist_prepend (other, obj);
1098 threadpool_jobs_dec (obj);
1102 threadpool_append_job (tp, (MonoObject *) mono_mlist_get_data (other));
1103 other = mono_mlist_next (other);
1108 * Clean up the threadpool of all domain jobs.
1109 * Can only be called as part of the domain unloading process as
1110 * it will wait for all jobs to be visible to the interruption code.
1113 mono_thread_pool_remove_domain_jobs (MonoDomain *domain, int timeout)
1117 guint32 start_time = 0;
1119 g_assert (domain->state == MONO_APPDOMAIN_UNLOADING);
1121 threadpool_clear_queue (&async_tp, domain);
1122 threadpool_clear_queue (&async_io_tp, domain);
1125 * There might be some threads out that could be about to execute stuff from the given domain.
1126 * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
1128 sem_handle = CreateSemaphore (NULL, 0, 1, NULL);
1130 domain->cleanup_semaphore = sem_handle;
1132 * The memory barrier here is required to have global ordering between assigning to cleanup_semaphone
1133 * and reading threadpool_jobs.
1134 * Otherwise this thread could read a stale version of threadpool_jobs and wait forever.
1136 mono_memory_write_barrier ();
1138 if (domain->threadpool_jobs && timeout != -1)
1139 start_time = mono_msec_ticks ();
1140 while (domain->threadpool_jobs) {
1141 WaitForSingleObject (sem_handle, timeout);
1142 if (timeout != -1 && (mono_msec_ticks () - start_time) > timeout) {
1148 domain->cleanup_semaphore = NULL;
1149 CloseHandle (sem_handle);
1154 threadpool_free_queue (ThreadPool *tp)
1156 mono_cq_destroy (tp->queue);
1161 mono_thread_pool_is_queue_array (MonoArray *o)
1163 // gpointer obj = o;
1165 // FIXME: need some fix in sgen code.
1175 EnterCriticalSection (&wsqs_lock);
1176 wsq = mono_wsq_create ();
1178 LeaveCriticalSection (&wsqs_lock);
1181 for (i = 0; i < wsqs->len; i++) {
1182 if (g_ptr_array_index (wsqs, i) == NULL) {
1183 wsqs->pdata [i] = wsq;
1184 LeaveCriticalSection (&wsqs_lock);
1188 g_ptr_array_add (wsqs, wsq);
1189 LeaveCriticalSection (&wsqs_lock);
1194 remove_wsq (MonoWSQ *wsq)
1201 EnterCriticalSection (&wsqs_lock);
1203 LeaveCriticalSection (&wsqs_lock);
1206 g_ptr_array_remove_fast (wsqs, wsq);
1209 * Only clean this up when shutting down, any other case will error out
1210 * if we're removing a queue that still has work items.
1212 if (mono_runtime_is_shutting_down ()) {
1213 while (mono_wsq_local_pop (&data)) {
1214 threadpool_jobs_dec (data);
1218 mono_wsq_destroy (wsq);
1219 LeaveCriticalSection (&wsqs_lock);
1223 try_steal (MonoWSQ *local_wsq, gpointer *data, gboolean retry)
1228 if (wsqs == NULL || data == NULL || *data != NULL)
1233 if (mono_runtime_is_shutting_down ())
1236 EnterCriticalSection (&wsqs_lock);
1237 for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
1240 wsq = wsqs->pdata [i];
1241 if (wsq == local_wsq || mono_wsq_count (wsq) == 0)
1243 mono_wsq_try_steal (wsqs->pdata [i], data, ms);
1244 if (*data != NULL) {
1245 LeaveCriticalSection (&wsqs_lock);
1249 LeaveCriticalSection (&wsqs_lock);
1251 } while (retry && ms < 11);
1255 dequeue_or_steal (ThreadPool *tp, gpointer *data, MonoWSQ *local_wsq)
1257 if (mono_runtime_is_shutting_down ())
1259 mono_cq_dequeue (tp->queue, (MonoObject **) data);
1260 if (!tp->is_io && !*data)
1261 try_steal (local_wsq, data, FALSE);
1262 return (*data != NULL);
1266 process_idle_times (ThreadPool *tp, gint64 t)
1270 gboolean compute_avg;
1274 if (tp->ignore_times || t <= 0)
1277 compute_avg = FALSE;
1278 ticks = mono_100ns_ticks ();
1280 SPIN_LOCK (tp->sp_lock);
1281 if (tp->ignore_times) {
1282 SPIN_UNLOCK (tp->sp_lock);
1287 if (tp->last_check == 0)
1288 tp->last_check = ticks;
1289 else if (tp->last_check > 0 && (ticks - tp->last_check) > 5000000) {
1290 tp->ignore_times = 1;
1293 SPIN_UNLOCK (tp->sp_lock);
1298 //printf ("Items: %d Time elapsed: %.3fs\n", tp->n_sum, (ticks - tp->last_check) / 10000.0);
1299 tp->last_check = ticks;
1301 avg = tp->time_sum / tp->n_sum;
1302 if (tp->averages [1] == 0) {
1303 tp->averages [1] = avg;
1305 per1 = ((100 * (ABS (avg - tp->averages [1]))) / tp->averages [1]);
1307 if (avg > tp->averages [1]) {
1308 if (tp->averages [1] < tp->averages [0]) {
1313 } else if (avg < tp->averages [1] && tp->averages [1] < tp->averages [0]) {
1318 min = tp->min_threads;
1320 if ((n - min) < min && tp->busy_threads == n)
1324 if (new_threads != 0) {
1325 printf ("n: %d per1: %lld avg=%lld avg1=%lld avg0=%lld\n", new_threads, per1, avg, tp->averages [1], tp->averages [0]);
1333 tp->averages [0] = tp->averages [1];
1334 tp->averages [1] = avg;
1335 tp->ignore_times = 0;
1337 if (new_threads == -1) {
1338 if (tp->destroy_thread == 0 && InterlockedCompareExchange (&tp->destroy_thread, 1, 0) == 0)
1339 pulse_on_new_job (tp);
1344 should_i_die (ThreadPool *tp)
1346 gboolean result = FALSE;
1347 if (tp->destroy_thread == 1 && InterlockedCompareExchange (&tp->destroy_thread, 0, 1) == 1)
1348 result = (tp->nthreads > tp->min_threads);
1353 async_invoke_thread (gpointer data)
1356 MonoInternalThread *thread;
1367 thread = mono_thread_internal_current ();
1369 mono_profiler_thread_start (thread->tid);
1370 name = (tp->is_io) ? "IO Threadpool worker" : "Threadpool worker";
1371 ves_icall_System_Threading_Thread_SetName_internal (thread, mono_string_new (mono_domain_get (), name));
1374 tp_start_func (tp_hooks_user_data);
1378 MonoAsyncResult *ar;
1380 gboolean is_io_task;
1385 ar = (MonoAsyncResult *) data;
1387 InterlockedIncrement (&tp->busy_threads);
1388 domain = ((MonoObject *)ar)->vtable->domain;
1389 #ifndef DISABLE_SOCKETS
1390 klass = ((MonoObject *) data)->vtable->klass;
1391 is_io_task = !is_corlib_asyncresult (domain, klass);
1394 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1395 is_socket = is_socketasyncresult (domain, klass);
1397 switch (state->operation) {
1398 case AIO_OP_RECEIVE:
1399 state->total = ICALL_RECV (state);
1402 state->total = ICALL_SEND (state);
1407 /* worker threads invokes methods in different domains,
1408 * so we need to set the right domain here */
1411 if (mono_domain_is_unloading (domain) || mono_runtime_is_shutting_down ()) {
1412 threadpool_jobs_dec ((MonoObject *)ar);
1415 InterlockedDecrement (&tp->busy_threads);
1417 mono_thread_push_appdomain_ref (domain);
1418 if (threadpool_jobs_dec ((MonoObject *)ar)) {
1421 mono_thread_pop_appdomain_ref ();
1422 InterlockedDecrement (&tp->busy_threads);
1426 if (mono_domain_set (domain, FALSE)) {
1429 if (tp_item_begin_func)
1430 tp_item_begin_func (tp_item_user_data);
1432 if (!is_io_task && ar->add_time > 0)
1433 process_idle_times (tp, ar->add_time);
1434 exc = mono_async_invoke (tp, ar);
1435 if (tp_item_end_func)
1436 tp_item_end_func (tp_item_user_data);
1437 if (exc && mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_CURRENT) {
1441 klass = exc->vtable->klass;
1442 unloaded = is_appdomainunloaded_exception (exc->vtable->domain, klass);
1443 if (!unloaded && klass != mono_defaults.threadabortexception_class) {
1444 mono_unhandled_exception (exc);
1445 if (mono_environment_exitcode_get () == 1)
1448 if (klass == mono_defaults.threadabortexception_class)
1449 mono_thread_internal_reset_abort (thread);
1451 if (is_socket && tp->is_io) {
1452 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1454 if (state->completed && state->callback) {
1455 MonoAsyncResult *cb_ares;
1456 cb_ares = create_simple_asyncresult ((MonoObject *) state->callback,
1457 (MonoObject *) state);
1458 icall_append_job ((MonoObject *) cb_ares);
1461 mono_domain_set (mono_get_root_domain (), TRUE);
1463 mono_thread_pop_appdomain_ref ();
1464 InterlockedDecrement (&tp->busy_threads);
1465 /* If the callee changes the background status, set it back to TRUE */
1466 mono_thread_clr_state (thread , ~ThreadState_Background);
1467 if (!mono_thread_test_state (thread , ThreadState_Background))
1468 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
1474 must_die = should_i_die (tp);
1475 if (!must_die && (tp->is_io || !mono_wsq_local_pop (&data)))
1476 dequeue_or_steal (tp, &data, wsq);
1479 while (!must_die && !data && n_naps < 4) {
1482 InterlockedIncrement (&tp->waiting);
1483 #if defined(__OpenBSD__)
1484 while (mono_cq_count (tp->queue) == 0 && (res = mono_sem_wait (&tp->new_job, TRUE)) == -1) {// && errno == EINTR) {
1486 while (mono_cq_count (tp->queue) == 0 && (res = mono_sem_timedwait (&tp->new_job, 2000, TRUE)) == -1) {// && errno == EINTR) {
1488 if (mono_runtime_is_shutting_down ())
1490 if (THREAD_WANTS_A_BREAK (thread))
1491 mono_thread_interruption_checkpoint ();
1493 InterlockedDecrement (&tp->waiting);
1494 if (mono_runtime_is_shutting_down ())
1496 must_die = should_i_die (tp);
1497 dequeue_or_steal (tp, &data, wsq);
1501 if (!data && !tp->is_io && !mono_runtime_is_shutting_down ()) {
1502 mono_wsq_local_pop (&data);
1503 if (data && must_die) {
1504 InterlockedCompareExchange (&tp->destroy_thread, 1, 0);
1505 pulse_on_new_job (tp);
1514 down = mono_runtime_is_shutting_down ();
1515 if (!down && nt <= tp->min_threads)
1517 if (down || InterlockedCompareExchange (&tp->nthreads, nt - 1, nt) == nt) {
1518 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, -1);
1523 mono_profiler_thread_end (thread->tid);
1526 tp_finish_func (tp_hooks_user_data);
1533 g_assert_not_reached ();
1537 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
1539 *workerThreads = async_tp.max_threads - async_tp.busy_threads;
1540 *completionPortThreads = async_io_tp.max_threads - async_io_tp.busy_threads;
1544 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
1546 *workerThreads = async_tp.max_threads;
1547 *completionPortThreads = async_io_tp.max_threads;
1551 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
1553 *workerThreads = async_tp.min_threads;
1554 *completionPortThreads = async_io_tp.min_threads;
1558 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
1561 gint max_io_threads;
1563 max_threads = async_tp.max_threads;
1564 if (workerThreads <= 0 || workerThreads > max_threads)
1567 max_io_threads = async_io_tp.max_threads;
1568 if (completionPortThreads <= 0 || completionPortThreads > max_io_threads)
1571 InterlockedExchange (&async_tp.min_threads, workerThreads);
1572 InterlockedExchange (&async_io_tp.min_threads, completionPortThreads);
1573 if (workerThreads > async_tp.nthreads)
1574 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_tp, TRUE, SMALL_STACK);
1575 if (completionPortThreads > async_io_tp.nthreads)
1576 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_io_tp, TRUE, SMALL_STACK);
1581 ves_icall_System_Threading_ThreadPool_SetMaxThreads (gint workerThreads, gint completionPortThreads)
1584 gint min_io_threads;
1587 cpu_count = mono_cpu_count ();
1588 min_threads = async_tp.min_threads;
1589 if (workerThreads < min_threads || workerThreads < cpu_count)
1592 /* We don't really have the concept of completion ports. Do we care here? */
1593 min_io_threads = async_io_tp.min_threads;
1594 if (completionPortThreads < min_io_threads || completionPortThreads < cpu_count)
1597 InterlockedExchange (&async_tp.max_threads, workerThreads);
1598 InterlockedExchange (&async_io_tp.max_threads, completionPortThreads);
1603 * mono_install_threadpool_thread_hooks
1604 * @start_func: the function to be called right after a new threadpool thread is created. Can be NULL.
1605 * @finish_func: the function to be called right before a thredpool thread is exiting. Can be NULL.
1606 * @user_data: argument passed to @start_func and @finish_func.
1608 * @start_fun will be called right after a threadpool thread is created and @finish_func right before a threadpool thread exits.
1609 * The calls will be made from the thread itself.
1612 mono_install_threadpool_thread_hooks (MonoThreadPoolFunc start_func, MonoThreadPoolFunc finish_func, gpointer user_data)
1614 tp_start_func = start_func;
1615 tp_finish_func = finish_func;
1616 tp_hooks_user_data = user_data;
1620 * mono_install_threadpool_item_hooks
1621 * @begin_func: the function to be called before a threadpool work item processing starts.
1622 * @end_func: the function to be called after a threadpool work item is finished.
1623 * @user_data: argument passed to @begin_func and @end_func.
1625 * The calls will be made from the thread itself and from the same AppDomain
1626 * where the work item was executed.
1630 mono_install_threadpool_item_hooks (MonoThreadPoolItemFunc begin_func, MonoThreadPoolItemFunc end_func, gpointer user_data)
1632 tp_item_begin_func = begin_func;
1633 tp_item_end_func = end_func;
1634 tp_item_user_data = user_data;