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;
164 static MonoThreadPoolFunc tp_start_func;
165 static MonoThreadPoolFunc tp_finish_func;
166 static gpointer tp_hooks_user_data;
167 static MonoThreadPoolItemFunc tp_item_begin_func;
168 static MonoThreadPoolItemFunc tp_item_end_func;
169 static gpointer tp_item_user_data;
179 AIO_OP_RECV_JUST_CALLBACK,
180 AIO_OP_SEND_JUST_CALLBACK,
184 AIO_OP_ACCEPTRECEIVE,
185 AIO_OP_RECEIVE_BUFFERS,
190 #include <mono/metadata/tpool-poll.c>
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;
217 * Note that we call it is_socket_type() where 'socket' refers to the image
218 * that contains the System.Net.Sockets.Socket type.
221 is_socket_type (MonoDomain *domain, MonoClass *klass)
223 return is_system_type (domain, klass);
226 #define check_type_cached(domain, ASSEMBLY, _class, _namespace, _name, loc) do { \
228 return *loc == _class; \
229 if (is_##ASSEMBLY##_type (domain, _class) && !strcmp (_name, _class->name) && !strcmp (_namespace, _class->name_space)) { \
236 #define check_corlib_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, corlib, _class, _namespace, _name, loc)
238 #define check_socket_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, socket, _class, _namespace, _name, loc)
240 #define check_system_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, system, _class, _namespace, _name, loc)
243 is_corlib_asyncresult (MonoDomain *domain, MonoClass *klass)
245 check_corlib_type_cached (domain, klass, "System.Runtime.Remoting.Messaging", "AsyncResult", &domain->corlib_asyncresult_class);
249 is_socket (MonoDomain *domain, MonoClass *klass)
251 check_socket_type_cached (domain, klass, "System.Net.Sockets", "Socket", &domain->socket_class);
255 is_socketasyncresult (MonoDomain *domain, MonoClass *klass)
257 return (klass->nested_in &&
258 is_socket (domain, klass->nested_in) &&
259 !strcmp (klass->name, "SocketAsyncResult"));
263 is_socketasynccall (MonoDomain *domain, MonoClass *klass)
265 return (klass->nested_in &&
266 is_socket (domain, klass->nested_in) &&
267 !strcmp (klass->name, "SocketAsyncCall"));
271 is_appdomainunloaded_exception (MonoDomain *domain, MonoClass *klass)
273 check_corlib_type_cached (domain, klass, "System", "AppDomainUnloadedException", &domain->ad_unloaded_ex_class);
277 is_sd_process (MonoDomain *domain, MonoClass *klass)
279 check_system_type_cached (domain, klass, "System.Diagnostics", "Process", &domain->process_class);
283 is_sdp_asyncreadhandler (MonoDomain *domain, MonoClass *klass)
286 return (klass->nested_in &&
287 is_sd_process (domain, klass->nested_in) &&
288 !strcmp (klass->name, "AsyncReadHandler"));
292 #ifdef DISABLE_SOCKETS
294 #define socket_io_cleanup(x)
297 get_event_from_state (MonoSocketAsyncResult *state)
299 g_assert_not_reached ();
304 get_events_from_list (MonoMList *list)
312 socket_io_cleanup (SocketIOData *data)
314 EnterCriticalSection (&data->io_lock);
315 if (data->inited != 2) {
316 LeaveCriticalSection (&data->io_lock);
320 data->shutdown (data->event_data);
321 LeaveCriticalSection (&data->io_lock);
325 get_event_from_state (MonoSocketAsyncResult *state)
327 switch (state->operation) {
330 case AIO_OP_RECV_JUST_CALLBACK:
331 case AIO_OP_RECEIVEFROM:
332 case AIO_OP_READPIPE:
333 case AIO_OP_ACCEPTRECEIVE:
334 case AIO_OP_RECEIVE_BUFFERS:
337 case AIO_OP_SEND_JUST_CALLBACK:
340 case AIO_OP_SEND_BUFFERS:
341 case AIO_OP_DISCONNECT:
343 default: /* Should never happen */
344 g_message ("get_event_from_state: unknown value in switch!!!");
350 get_events_from_list (MonoMList *list)
352 MonoSocketAsyncResult *state;
355 while (list && (state = (MonoSocketAsyncResult *)mono_mlist_get_data (list))) {
356 events |= get_event_from_state (state);
357 list = mono_mlist_next (list);
363 #define ICALL_RECV(x) ves_icall_System_Net_Sockets_Socket_Receive_internal (\
364 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
365 x->socket_flags, &x->error);
367 #define ICALL_SEND(x) ves_icall_System_Net_Sockets_Socket_Send_internal (\
368 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
369 x->socket_flags, &x->error);
371 #endif /* !DISABLE_SOCKETS */
374 threadpool_jobs_inc (MonoObject *obj)
377 InterlockedIncrement (&obj->vtable->domain->threadpool_jobs);
381 threadpool_jobs_dec (MonoObject *obj)
389 domain = obj->vtable->domain;
390 remaining_jobs = InterlockedDecrement (&domain->threadpool_jobs);
391 if (remaining_jobs == 0 && domain->cleanup_semaphore) {
392 ReleaseSemaphore (domain->cleanup_semaphore, 1, NULL);
399 get_io_event (MonoMList **list, gint event)
409 state = mono_mlist_get_data (current);
410 if (get_event_from_state ((MonoSocketAsyncResult *) state) == event)
415 current = mono_mlist_next (current);
420 mono_mlist_set_next (prev, mono_mlist_next (current));
422 *list = mono_mlist_next (*list);
430 * select/poll wake up when a socket is closed, but epoll just removes
431 * the socket from its internal list without notification.
434 mono_thread_pool_remove_socket (int sock)
437 MonoSocketAsyncResult *state;
440 if (socket_io_data.inited == 0)
443 EnterCriticalSection (&socket_io_data.io_lock);
444 if (socket_io_data.sock_to_state == NULL) {
445 LeaveCriticalSection (&socket_io_data.io_lock);
448 list = mono_g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
450 mono_g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
451 LeaveCriticalSection (&socket_io_data.io_lock);
454 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
455 if (state->operation == AIO_OP_RECEIVE)
456 state->operation = AIO_OP_RECV_JUST_CALLBACK;
457 else if (state->operation == AIO_OP_SEND)
458 state->operation = AIO_OP_SEND_JUST_CALLBACK;
460 ares = get_io_event (&list, MONO_POLLIN);
461 threadpool_append_job (&async_io_tp, ares);
463 ares = get_io_event (&list, MONO_POLLOUT);
464 threadpool_append_job (&async_io_tp, ares);
470 init_event_system (SocketIOData *data)
473 if (data->event_system == EPOLL_BACKEND) {
474 data->event_data = tp_epoll_init (data);
475 if (data->event_data == NULL) {
476 if (g_getenv ("MONO_DEBUG"))
477 g_message ("Falling back to poll()");
478 data->event_system = POLL_BACKEND;
481 #elif defined(USE_KQUEUE_FOR_THREADPOOL)
482 if (data->event_system == KQUEUE_BACKEND)
483 data->event_data = tp_kqueue_init (data);
485 if (data->event_system == POLL_BACKEND)
486 data->event_data = tp_poll_init (data);
490 socket_io_init (SocketIOData *data)
494 if (data->inited >= 2) // 2 -> initialized, 3-> cleaned up
497 inited = InterlockedCompareExchange (&data->inited, 1, 0);
500 if (data->inited >= 2)
506 EnterCriticalSection (&data->io_lock);
507 data->sock_to_state = mono_g_hash_table_new_type (g_direct_hash, g_direct_equal, MONO_HASH_VALUE_GC);
509 data->event_system = EPOLL_BACKEND;
510 #elif defined(USE_KQUEUE_FOR_THREADPOOL)
511 data->event_system = KQUEUE_BACKEND;
513 data->event_system = POLL_BACKEND;
515 if (g_getenv ("MONO_DISABLE_AIO") != NULL)
516 data->event_system = POLL_BACKEND;
518 init_event_system (data);
519 mono_thread_create_internal (mono_get_root_domain (), data->wait, data, TRUE, FALSE, SMALL_STACK);
520 LeaveCriticalSection (&data->io_lock);
522 threadpool_start_thread (&async_io_tp);
526 socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
529 SocketIOData *data = &socket_io_data;
534 socket_io_init (&socket_io_data);
535 if (mono_runtime_is_shutting_down () || data->inited == 3 || data->sock_to_state == NULL)
537 if (async_tp.pool_status == 2)
540 MONO_OBJECT_SETREF (state, ares, ares);
542 fd = GPOINTER_TO_INT (state->handle);
543 EnterCriticalSection (&data->io_lock);
544 if (data->sock_to_state == NULL) {
545 LeaveCriticalSection (&data->io_lock);
548 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
550 list = mono_mlist_alloc ((MonoObject*)state);
553 list = mono_mlist_append (list, (MonoObject*)state);
557 mono_g_hash_table_replace (data->sock_to_state, state->handle, list);
558 ievt = get_events_from_list (list);
559 LeaveCriticalSection (&data->io_lock);
560 data->modify (data->event_data, fd, state->operation, ievt, is_new);
563 #ifndef DISABLE_SOCKETS
565 socket_io_filter (MonoObject *target, MonoObject *state)
568 MonoSocketAsyncResult *sock_res;
572 if (target == NULL || state == NULL)
575 domain = target->vtable->domain;
576 klass = target->vtable->klass;
577 if (socket_async_call_klass == NULL && is_socketasynccall (domain, klass))
578 socket_async_call_klass = klass;
580 if (process_async_call_klass == NULL && is_sdp_asyncreadhandler (domain, klass))
581 process_async_call_klass = klass;
583 if (klass != socket_async_call_klass && klass != process_async_call_klass)
586 sock_res = (MonoSocketAsyncResult *) state;
587 op = sock_res->operation;
588 if (op < AIO_OP_FIRST || op >= AIO_OP_LAST)
593 #endif /* !DISABLE_SOCKETS */
595 /* Returns the exception thrown when invoking, if any */
597 mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares)
599 ASyncCall *ac = (ASyncCall *)ares->object_data;
600 MonoObject *res, *exc = NULL;
601 MonoArray *out_args = NULL;
602 HANDLE wait_event = NULL;
604 if (ares->execution_context) {
605 /* use captured ExecutionContext (if available) */
606 MONO_OBJECT_SETREF (ares, original_context, mono_thread_get_execution_context ());
607 mono_thread_set_execution_context (ares->execution_context);
609 ares->original_context = NULL;
613 /* Fast path from ThreadPool.*QueueUserWorkItem */
614 void *pa = ares->async_state;
615 res = mono_runtime_delegate_invoke (ares->async_delegate, &pa, &exc);
617 MonoObject *cb_exc = NULL;
620 res = mono_message_invoke (ares->async_delegate, ac->msg, &exc, &out_args);
621 MONO_OBJECT_SETREF (ac, res, res);
622 MONO_OBJECT_SETREF (ac, msg->exc, exc);
623 MONO_OBJECT_SETREF (ac, out_args, out_args);
625 mono_monitor_enter ((MonoObject *) ares);
627 if (ares->handle != NULL)
628 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
629 mono_monitor_exit ((MonoObject *) ares);
630 /* notify listeners */
631 if (wait_event != NULL)
632 SetEvent (wait_event);
634 /* call async callback if cb_method != null*/
635 if (ac != NULL && ac->cb_method) {
638 mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &cb_exc);
645 /* restore original thread execution context if flow isn't suppressed, i.e. non null */
646 if (ares->original_context) {
647 mono_thread_set_execution_context (ares->original_context);
648 ares->original_context = NULL;
654 threadpool_start_idle_threads (ThreadPool *tp)
659 stack_size = (!tp->is_io) ? 0 : SMALL_STACK;
663 if (n >= tp->min_threads)
665 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n)
668 #ifndef DISABLE_PERFCOUNTERS
669 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
671 mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE, FALSE, stack_size);
677 threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer))
679 memset (tp, 0, sizeof (ThreadPool));
680 tp->min_threads = min_threads;
681 tp->max_threads = max_threads;
682 tp->async_invoke = async_invoke;
683 tp->queue = mono_cq_create ();
684 MONO_SEM_INIT (&tp->new_job, 0);
687 #ifndef DISABLE_PERFCOUNTERS
689 init_perf_counter (const char *category, const char *counter)
691 MonoString *category_str;
692 MonoString *counter_str;
698 if (category == NULL || counter == NULL)
700 root = mono_get_root_domain ();
701 category_str = mono_string_new (root, category);
702 counter_str = mono_string_new (root, counter);
703 machine = mono_string_new (root, ".");
704 return mono_perfcounter_get_impl (category_str, counter_str, NULL, machine, &type, &custom);
710 print_pool_info (ThreadPool *tp)
713 // if (tp->tail - tp->head == 0)
716 g_print ("Pool status? %d\n", InterlockedCompareExchange (&tp->pool_status, 0, 0));
717 g_print ("Min. threads: %d\n", InterlockedCompareExchange (&tp->min_threads, 0, 0));
718 g_print ("Max. threads: %d\n", InterlockedCompareExchange (&tp->max_threads, 0, 0));
719 g_print ("nthreads: %d\n", InterlockedCompareExchange (&tp->nthreads, 0, 0));
720 g_print ("busy threads: %d\n", InterlockedCompareExchange (&tp->busy_threads, 0, 0));
721 g_print ("Waiting: %d\n", InterlockedCompareExchange (&tp->waiting, 0, 0));
722 g_print ("Queued: %d\n", (tp->tail - tp->head));
723 if (tp == &async_tp) {
725 EnterCriticalSection (&wsqs_lock);
726 for (i = 0; i < wsqs->len; i++) {
727 g_print ("\tWSQ %d: %d\n", i, mono_wsq_count (g_ptr_array_index (wsqs, i)));
729 LeaveCriticalSection (&wsqs_lock);
731 g_print ("\tSockets: %d\n", mono_g_hash_table_size (socket_io_data.sock_to_state));
733 g_print ("-------------\n");
737 signal_handler (int signo)
742 g_print ("\n-----Non-IO-----\n");
743 print_pool_info (tp);
745 g_print ("\n-----IO-----\n");
746 print_pool_info (tp);
752 monitor_thread (gpointer unused)
754 ThreadPool *pools [2];
755 MonoInternalThread *thread;
760 pools [0] = &async_tp;
761 pools [1] = &async_io_tp;
762 thread = mono_thread_internal_current ();
763 ves_icall_System_Threading_Thread_SetName_internal (thread, mono_string_new (mono_domain_get (), "Threadpool monitor"));
768 ts = mono_msec_ticks ();
769 if (SleepEx (ms, TRUE) == 0)
771 ms -= (mono_msec_ticks () - ts);
772 if (mono_runtime_is_shutting_down ())
774 if (THREAD_WANTS_A_BREAK (thread))
775 mono_thread_interruption_checkpoint ();
778 if (mono_runtime_is_shutting_down ())
781 for (i = 0; i < 2; i++) {
786 need_one = (mono_cq_count (tp->queue) > 0);
787 if (!need_one && !tp->is_io) {
788 EnterCriticalSection (&wsqs_lock);
789 for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
791 wsq = g_ptr_array_index (wsqs, i);
792 if (mono_wsq_count (wsq) != 0) {
797 LeaveCriticalSection (&wsqs_lock);
800 threadpool_start_thread (tp);
806 mono_thread_pool_init ()
808 gint threads_per_cpu = 1;
810 gint cpu_count = mono_cpu_count ();
816 result = InterlockedCompareExchange (&tp_inited, 1, 0);
825 MONO_GC_REGISTER_ROOT_FIXED (socket_io_data.sock_to_state);
826 InitializeCriticalSection (&socket_io_data.io_lock);
827 if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
828 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
829 if (threads_per_cpu < 1)
833 thread_count = MIN (cpu_count * threads_per_cpu, 100 * cpu_count);
834 threadpool_init (&async_tp, thread_count, MAX (100 * cpu_count, thread_count), async_invoke_thread);
835 threadpool_init (&async_io_tp, cpu_count * 2, cpu_count * 4, async_invoke_thread);
836 async_io_tp.is_io = TRUE;
838 async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
839 g_assert (async_call_klass);
841 InitializeCriticalSection (&wsqs_lock);
842 wsqs = g_ptr_array_sized_new (MAX (100 * cpu_count, thread_count));
845 #ifndef DISABLE_PERFCOUNTERS
846 async_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "Work Items Added");
847 g_assert (async_tp.pc_nitems);
849 async_io_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "IO Work Items Added");
850 g_assert (async_io_tp.pc_nitems);
852 async_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of Threads");
853 g_assert (async_tp.pc_nthreads);
855 async_io_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of IO Threads");
856 g_assert (async_io_tp.pc_nthreads);
860 signal (SIGALRM, signal_handler);
865 static MonoAsyncResult *
866 create_simple_asyncresult (MonoObject *target, MonoObject *state)
868 MonoDomain *domain = mono_domain_get ();
869 MonoAsyncResult *ares;
871 /* Don't call mono_async_result_new() to avoid capturing the context */
872 ares = (MonoAsyncResult *) mono_object_new (domain, mono_defaults.asyncresult_class);
873 MONO_OBJECT_SETREF (ares, async_delegate, target);
874 MONO_OBJECT_SETREF (ares, async_state, state);
879 icall_append_io_job (MonoObject *target, MonoSocketAsyncResult *state)
881 MonoAsyncResult *ares;
883 ares = create_simple_asyncresult (target, (MonoObject *) state);
884 socket_io_add (ares, state);
888 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
891 MonoDomain *domain = mono_domain_get ();
892 MonoAsyncResult *ares;
895 ac = (ASyncCall*)mono_object_new (domain, async_call_klass);
896 MONO_OBJECT_SETREF (ac, msg, msg);
897 MONO_OBJECT_SETREF (ac, state, state);
899 if (async_callback) {
900 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
901 MONO_OBJECT_SETREF (ac, cb_target, async_callback);
904 ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
905 MONO_OBJECT_SETREF (ares, async_delegate, target);
907 #ifndef DISABLE_SOCKETS
908 if (socket_io_filter (target, state)) {
909 socket_io_add (ares, (MonoSocketAsyncResult *) state);
913 threadpool_append_job (&async_tp, (MonoObject *) ares);
918 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
926 /* check if already finished */
927 mono_monitor_enter ((MonoObject *) ares);
929 if (ares->endinvoke_called) {
930 *exc = (MonoObject *) mono_get_exception_invalid_operation (NULL);
931 mono_monitor_exit ((MonoObject *) ares);
935 ares->endinvoke_called = 1;
936 /* wait until we are really finished */
937 if (!ares->completed) {
938 if (ares->handle == NULL) {
939 wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
940 g_assert(wait_event != 0);
941 MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), wait_event));
943 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
945 mono_monitor_exit ((MonoObject *) ares);
946 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
948 mono_monitor_exit ((MonoObject *) ares);
951 ac = (ASyncCall *) ares->object_data;
952 g_assert (ac != NULL);
953 *exc = ac->msg->exc; /* FIXME: GC add write barrier */
954 *out_args = ac->out_args;
960 threadpool_kill_idle_threads (ThreadPool *tp)
964 n = (gint) InterlockedCompareExchange (&tp->max_threads, 0, -1);
967 MONO_SEM_POST (&tp->new_job);
972 mono_thread_pool_cleanup (void)
974 if (InterlockedExchange (&async_io_tp.pool_status, 2) == 1) {
975 socket_io_cleanup (&socket_io_data); /* Empty when DISABLE_SOCKETS is defined */
976 threadpool_kill_idle_threads (&async_io_tp);
979 if (async_io_tp.queue != NULL) {
980 MONO_SEM_DESTROY (&async_io_tp.new_job);
981 threadpool_free_queue (&async_io_tp);
985 if (InterlockedExchange (&async_tp.pool_status, 2) == 1) {
986 threadpool_kill_idle_threads (&async_tp);
987 threadpool_free_queue (&async_tp);
991 EnterCriticalSection (&wsqs_lock);
994 g_ptr_array_free (wsqs, TRUE);
996 LeaveCriticalSection (&wsqs_lock);
997 MONO_SEM_DESTROY (&async_tp.new_job);
1002 threadpool_start_thread (ThreadPool *tp)
1007 stack_size = (!tp->is_io) ? 0 : SMALL_STACK;
1008 while (!mono_runtime_is_shutting_down () && (n = tp->nthreads) < tp->max_threads) {
1009 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n) {
1010 #ifndef DISABLE_PERFCOUNTERS
1011 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
1013 mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE, FALSE, stack_size);
1022 pulse_on_new_job (ThreadPool *tp)
1025 MONO_SEM_POST (&tp->new_job);
1029 icall_append_job (MonoObject *ar)
1031 threadpool_append_jobs (&async_tp, &ar, 1);
1035 threadpool_append_job (ThreadPool *tp, MonoObject *ar)
1037 threadpool_append_jobs (tp, &ar, 1);
1041 threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs)
1043 static int job_counter;
1047 if (mono_runtime_is_shutting_down ())
1050 if (tp->pool_status == 0 && InterlockedCompareExchange (&tp->pool_status, 1, 0) == 0) {
1052 mono_thread_create_internal (mono_get_root_domain (), monitor_thread, NULL, TRUE, FALSE, SMALL_STACK);
1053 threadpool_start_thread (tp);
1055 /* Create on demand up to min_threads to avoid startup penalty for apps that don't use
1056 * the threadpool that much
1057 * mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, tp, TRUE, FALSE, SMALL_STACK);
1061 for (i = 0; i < njobs; i++) {
1063 if (ar == NULL || mono_domain_is_unloading (ar->vtable->domain))
1064 continue; /* Might happen when cleaning domain jobs */
1065 if (!tp->is_io && (InterlockedIncrement (&job_counter) % 10) == 0) {
1066 MonoAsyncResult *o = (MonoAsyncResult *) ar;
1067 o->add_time = mono_100ns_ticks ();
1069 threadpool_jobs_inc (ar);
1070 #ifndef DISABLE_PERFCOUNTERS
1071 mono_perfcounter_update_value (tp->pc_nitems, TRUE, 1);
1073 if (!tp->is_io && mono_wsq_local_push (ar))
1076 mono_cq_enqueue (tp->queue, ar);
1079 for (i = 0; tp->waiting > 0 && i < MIN(njobs, tp->max_threads); i++)
1080 pulse_on_new_job (tp);
1084 threadpool_clear_queue (ThreadPool *tp, MonoDomain *domain)
1090 while (mono_cq_dequeue (tp->queue, &obj)) {
1093 if (obj->vtable->domain != domain)
1094 other = mono_mlist_prepend (other, obj);
1095 threadpool_jobs_dec (obj);
1099 threadpool_append_job (tp, (MonoObject *) mono_mlist_get_data (other));
1100 other = mono_mlist_next (other);
1105 remove_sockstate_for_domain (gpointer key, gpointer value, gpointer user_data)
1107 MonoMList *list = value;
1108 gboolean remove = FALSE;
1110 MonoObject *data = mono_mlist_get_data (list);
1111 if (mono_object_domain (data) == user_data) {
1113 mono_mlist_set_data (list, NULL);
1115 list = mono_mlist_next (list);
1117 //FIXME is there some sort of additional unregistration we need to perform here?
1122 * Clean up the threadpool of all domain jobs.
1123 * Can only be called as part of the domain unloading process as
1124 * it will wait for all jobs to be visible to the interruption code.
1127 mono_thread_pool_remove_domain_jobs (MonoDomain *domain, int timeout)
1131 guint32 start_time = 0;
1133 g_assert (domain->state == MONO_APPDOMAIN_UNLOADING);
1135 threadpool_clear_queue (&async_tp, domain);
1136 threadpool_clear_queue (&async_io_tp, domain);
1138 EnterCriticalSection (&socket_io_data.io_lock);
1139 if (socket_io_data.sock_to_state)
1140 mono_g_hash_table_foreach_remove (socket_io_data.sock_to_state, remove_sockstate_for_domain, domain);
1142 LeaveCriticalSection (&socket_io_data.io_lock);
1145 * There might be some threads out that could be about to execute stuff from the given domain.
1146 * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
1148 sem_handle = CreateSemaphore (NULL, 0, 1, NULL);
1150 domain->cleanup_semaphore = sem_handle;
1152 * The memory barrier here is required to have global ordering between assigning to cleanup_semaphone
1153 * and reading threadpool_jobs.
1154 * Otherwise this thread could read a stale version of threadpool_jobs and wait forever.
1156 mono_memory_write_barrier ();
1158 if (domain->threadpool_jobs && timeout != -1)
1159 start_time = mono_msec_ticks ();
1160 while (domain->threadpool_jobs) {
1161 WaitForSingleObject (sem_handle, timeout);
1162 if (timeout != -1 && (mono_msec_ticks () - start_time) > timeout) {
1168 domain->cleanup_semaphore = NULL;
1169 CloseHandle (sem_handle);
1174 threadpool_free_queue (ThreadPool *tp)
1176 mono_cq_destroy (tp->queue);
1181 mono_thread_pool_is_queue_array (MonoArray *o)
1183 // gpointer obj = o;
1185 // FIXME: need some fix in sgen code.
1195 EnterCriticalSection (&wsqs_lock);
1196 wsq = mono_wsq_create ();
1198 LeaveCriticalSection (&wsqs_lock);
1201 for (i = 0; i < wsqs->len; i++) {
1202 if (g_ptr_array_index (wsqs, i) == NULL) {
1203 wsqs->pdata [i] = wsq;
1204 LeaveCriticalSection (&wsqs_lock);
1208 g_ptr_array_add (wsqs, wsq);
1209 LeaveCriticalSection (&wsqs_lock);
1214 remove_wsq (MonoWSQ *wsq)
1221 EnterCriticalSection (&wsqs_lock);
1223 LeaveCriticalSection (&wsqs_lock);
1226 g_ptr_array_remove_fast (wsqs, wsq);
1229 * Only clean this up when shutting down, any other case will error out
1230 * if we're removing a queue that still has work items.
1232 if (mono_runtime_is_shutting_down ()) {
1233 while (mono_wsq_local_pop (&data)) {
1234 threadpool_jobs_dec (data);
1238 mono_wsq_destroy (wsq);
1239 LeaveCriticalSection (&wsqs_lock);
1243 try_steal (MonoWSQ *local_wsq, gpointer *data, gboolean retry)
1248 if (wsqs == NULL || data == NULL || *data != NULL)
1253 if (mono_runtime_is_shutting_down ())
1256 EnterCriticalSection (&wsqs_lock);
1257 for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
1260 wsq = wsqs->pdata [i];
1261 if (wsq == local_wsq || mono_wsq_count (wsq) == 0)
1263 mono_wsq_try_steal (wsqs->pdata [i], data, ms);
1264 if (*data != NULL) {
1265 LeaveCriticalSection (&wsqs_lock);
1269 LeaveCriticalSection (&wsqs_lock);
1271 } while (retry && ms < 11);
1275 dequeue_or_steal (ThreadPool *tp, gpointer *data, MonoWSQ *local_wsq)
1277 if (mono_runtime_is_shutting_down ())
1279 mono_cq_dequeue (tp->queue, (MonoObject **) data);
1280 if (!tp->is_io && !*data)
1281 try_steal (local_wsq, data, FALSE);
1282 return (*data != NULL);
1286 process_idle_times (ThreadPool *tp, gint64 t)
1290 gboolean compute_avg;
1294 if (tp->ignore_times || t <= 0)
1297 compute_avg = FALSE;
1298 ticks = mono_100ns_ticks ();
1300 SPIN_LOCK (tp->sp_lock);
1301 if (tp->ignore_times) {
1302 SPIN_UNLOCK (tp->sp_lock);
1307 if (tp->last_check == 0)
1308 tp->last_check = ticks;
1309 else if (tp->last_check > 0 && (ticks - tp->last_check) > 5000000) {
1310 tp->ignore_times = 1;
1313 SPIN_UNLOCK (tp->sp_lock);
1318 //printf ("Items: %d Time elapsed: %.3fs\n", tp->n_sum, (ticks - tp->last_check) / 10000.0);
1319 tp->last_check = ticks;
1321 avg = tp->time_sum / tp->n_sum;
1322 if (tp->averages [1] == 0) {
1323 tp->averages [1] = avg;
1325 per1 = ((100 * (ABS (avg - tp->averages [1]))) / tp->averages [1]);
1327 if (avg > tp->averages [1]) {
1328 if (tp->averages [1] < tp->averages [0]) {
1333 } else if (avg < tp->averages [1] && tp->averages [1] < tp->averages [0]) {
1338 min = tp->min_threads;
1340 if ((n - min) < min && tp->busy_threads == n)
1344 if (new_threads != 0) {
1345 printf ("n: %d per1: %lld avg=%lld avg1=%lld avg0=%lld\n", new_threads, per1, avg, tp->averages [1], tp->averages [0]);
1353 tp->averages [0] = tp->averages [1];
1354 tp->averages [1] = avg;
1355 tp->ignore_times = 0;
1357 if (new_threads == -1) {
1358 if (tp->destroy_thread == 0 && InterlockedCompareExchange (&tp->destroy_thread, 1, 0) == 0)
1359 pulse_on_new_job (tp);
1364 should_i_die (ThreadPool *tp)
1366 gboolean result = FALSE;
1367 if (tp->destroy_thread == 1 && InterlockedCompareExchange (&tp->destroy_thread, 0, 1) == 1)
1368 result = (tp->nthreads > tp->min_threads);
1373 async_invoke_thread (gpointer data)
1376 MonoInternalThread *thread;
1387 thread = mono_thread_internal_current ();
1389 mono_profiler_thread_start (thread->tid);
1390 name = (tp->is_io) ? "IO Threadpool worker" : "Threadpool worker";
1391 mono_thread_set_name_internal (thread, mono_string_new (mono_domain_get (), name), FALSE);
1394 tp_start_func (tp_hooks_user_data);
1398 MonoAsyncResult *ar;
1400 gboolean is_io_task;
1405 ar = (MonoAsyncResult *) data;
1407 InterlockedIncrement (&tp->busy_threads);
1408 domain = ((MonoObject *)ar)->vtable->domain;
1409 #ifndef DISABLE_SOCKETS
1410 klass = ((MonoObject *) data)->vtable->klass;
1411 is_io_task = !is_corlib_asyncresult (domain, klass);
1414 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1415 is_socket = is_socketasyncresult (domain, klass);
1417 switch (state->operation) {
1418 case AIO_OP_RECEIVE:
1419 state->total = ICALL_RECV (state);
1422 state->total = ICALL_SEND (state);
1427 /* worker threads invokes methods in different domains,
1428 * so we need to set the right domain here */
1431 if (mono_domain_is_unloading (domain) || mono_runtime_is_shutting_down ()) {
1432 threadpool_jobs_dec ((MonoObject *)ar);
1435 InterlockedDecrement (&tp->busy_threads);
1437 mono_thread_push_appdomain_ref (domain);
1438 if (threadpool_jobs_dec ((MonoObject *)ar)) {
1441 mono_thread_pop_appdomain_ref ();
1442 InterlockedDecrement (&tp->busy_threads);
1446 if (mono_domain_set (domain, FALSE)) {
1449 if (tp_item_begin_func)
1450 tp_item_begin_func (tp_item_user_data);
1452 if (!is_io_task && ar->add_time > 0)
1453 process_idle_times (tp, ar->add_time);
1454 exc = mono_async_invoke (tp, ar);
1455 if (tp_item_end_func)
1456 tp_item_end_func (tp_item_user_data);
1458 mono_internal_thread_unhandled_exception (exc);
1459 if (is_socket && tp->is_io) {
1460 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1462 if (state->completed && state->callback) {
1463 MonoAsyncResult *cb_ares;
1464 cb_ares = create_simple_asyncresult ((MonoObject *) state->callback,
1465 (MonoObject *) state);
1466 icall_append_job ((MonoObject *) cb_ares);
1469 mono_domain_set (mono_get_root_domain (), TRUE);
1471 mono_thread_pop_appdomain_ref ();
1472 InterlockedDecrement (&tp->busy_threads);
1473 /* If the callee changes the background status, set it back to TRUE */
1474 mono_thread_clr_state (thread , ~ThreadState_Background);
1475 if (!mono_thread_test_state (thread , ThreadState_Background))
1476 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
1482 must_die = should_i_die (tp);
1483 if (!must_die && (tp->is_io || !mono_wsq_local_pop (&data)))
1484 dequeue_or_steal (tp, &data, wsq);
1487 while (!must_die && !data && n_naps < 4) {
1490 InterlockedIncrement (&tp->waiting);
1492 // Another thread may have added a job into its wsq since the last call to dequeue_or_steal
1493 // Check all the queues again before entering the wait loop
1494 dequeue_or_steal (tp, &data, wsq);
1496 InterlockedDecrement (&tp->waiting);
1500 mono_gc_set_skip_thread (TRUE);
1502 #if defined(__OpenBSD__)
1503 while (mono_cq_count (tp->queue) == 0 && (res = mono_sem_wait (&tp->new_job, TRUE)) == -1) {// && errno == EINTR) {
1505 while (mono_cq_count (tp->queue) == 0 && (res = mono_sem_timedwait (&tp->new_job, 2000, TRUE)) == -1) {// && errno == EINTR) {
1507 if (mono_runtime_is_shutting_down ())
1509 if (THREAD_WANTS_A_BREAK (thread))
1510 mono_thread_interruption_checkpoint ();
1512 InterlockedDecrement (&tp->waiting);
1514 mono_gc_set_skip_thread (FALSE);
1516 if (mono_runtime_is_shutting_down ())
1518 must_die = should_i_die (tp);
1519 dequeue_or_steal (tp, &data, wsq);
1523 if (!data && !tp->is_io && !mono_runtime_is_shutting_down ()) {
1524 mono_wsq_local_pop (&data);
1525 if (data && must_die) {
1526 InterlockedCompareExchange (&tp->destroy_thread, 1, 0);
1527 pulse_on_new_job (tp);
1536 down = mono_runtime_is_shutting_down ();
1537 if (!down && nt <= tp->min_threads)
1539 if (down || InterlockedCompareExchange (&tp->nthreads, nt - 1, nt) == nt) {
1540 #ifndef DISABLE_PERFCOUNTERS
1541 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, -1);
1547 mono_profiler_thread_end (thread->tid);
1550 tp_finish_func (tp_hooks_user_data);
1557 g_assert_not_reached ();
1561 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
1563 *workerThreads = async_tp.max_threads - async_tp.busy_threads;
1564 *completionPortThreads = async_io_tp.max_threads - async_io_tp.busy_threads;
1568 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
1570 *workerThreads = async_tp.max_threads;
1571 *completionPortThreads = async_io_tp.max_threads;
1575 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
1577 *workerThreads = async_tp.min_threads;
1578 *completionPortThreads = async_io_tp.min_threads;
1582 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
1585 gint max_io_threads;
1587 max_threads = async_tp.max_threads;
1588 if (workerThreads <= 0 || workerThreads > max_threads)
1591 max_io_threads = async_io_tp.max_threads;
1592 if (completionPortThreads <= 0 || completionPortThreads > max_io_threads)
1595 InterlockedExchange (&async_tp.min_threads, workerThreads);
1596 InterlockedExchange (&async_io_tp.min_threads, completionPortThreads);
1597 if (workerThreads > async_tp.nthreads)
1598 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_tp, TRUE, FALSE, SMALL_STACK);
1599 if (completionPortThreads > async_io_tp.nthreads)
1600 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_io_tp, TRUE, FALSE, SMALL_STACK);
1605 ves_icall_System_Threading_ThreadPool_SetMaxThreads (gint workerThreads, gint completionPortThreads)
1608 gint min_io_threads;
1611 cpu_count = mono_cpu_count ();
1612 min_threads = async_tp.min_threads;
1613 if (workerThreads < min_threads || workerThreads < cpu_count)
1616 /* We don't really have the concept of completion ports. Do we care here? */
1617 min_io_threads = async_io_tp.min_threads;
1618 if (completionPortThreads < min_io_threads || completionPortThreads < cpu_count)
1621 InterlockedExchange (&async_tp.max_threads, workerThreads);
1622 InterlockedExchange (&async_io_tp.max_threads, completionPortThreads);
1627 * mono_install_threadpool_thread_hooks
1628 * @start_func: the function to be called right after a new threadpool thread is created. Can be NULL.
1629 * @finish_func: the function to be called right before a thredpool thread is exiting. Can be NULL.
1630 * @user_data: argument passed to @start_func and @finish_func.
1632 * @start_fun will be called right after a threadpool thread is created and @finish_func right before a threadpool thread exits.
1633 * The calls will be made from the thread itself.
1636 mono_install_threadpool_thread_hooks (MonoThreadPoolFunc start_func, MonoThreadPoolFunc finish_func, gpointer user_data)
1638 tp_start_func = start_func;
1639 tp_finish_func = finish_func;
1640 tp_hooks_user_data = user_data;
1644 * mono_install_threadpool_item_hooks
1645 * @begin_func: the function to be called before a threadpool work item processing starts.
1646 * @end_func: the function to be called after a threadpool work item is finished.
1647 * @user_data: argument passed to @begin_func and @end_func.
1649 * The calls will be made from the thread itself and from the same AppDomain
1650 * where the work item was executed.
1654 mono_install_threadpool_item_hooks (MonoThreadPoolItemFunc begin_func, MonoThreadPoolItemFunc end_func, gpointer user_data)
1656 tp_item_begin_func = begin_func;
1657 tp_item_end_func = end_func;
1658 tp_item_user_data = user_data;
1662 mono_internal_thread_unhandled_exception (MonoObject* exc)
1664 if (mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_CURRENT) {
1668 klass = exc->vtable->klass;
1669 unloaded = is_appdomainunloaded_exception (exc->vtable->domain, klass);
1670 if (!unloaded && klass != mono_defaults.threadabortexception_class) {
1671 mono_unhandled_exception (exc);
1672 if (mono_environment_exitcode_get () == 1)
1675 if (klass == mono_defaults.threadabortexception_class)
1676 mono_thread_internal_reset_abort (mono_thread_internal_current ());