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)
15 #ifdef MONO_SMALL_CONFIG
16 #define QUEUE_LENGTH 16 /* Must be 2^N */
18 #define QUEUE_LENGTH 64 /* Must be 2^N */
21 #include <mono/metadata/domain-internals.h>
22 #include <mono/metadata/profiler-private.h>
23 #include <mono/metadata/tabledefs.h>
24 #include <mono/metadata/threads.h>
25 #include <mono/metadata/threads-types.h>
26 #include <mono/metadata/threadpool-internals.h>
27 #include <mono/metadata/exception.h>
28 #include <mono/metadata/file-io.h>
29 #include <mono/metadata/monitor.h>
30 #include <mono/metadata/mono-mlist.h>
31 #include <mono/metadata/marshal.h>
32 #include <mono/metadata/mono-perfcounters.h>
33 #include <mono/metadata/socket-io.h>
34 #include <mono/metadata/mono-wsq.h>
35 #include <mono/io-layer/io-layer.h>
36 #include <mono/metadata/gc-internal.h>
37 #include <mono/utils/mono-time.h>
38 #include <mono/utils/mono-proclib.h>
39 #include <mono/utils/mono-semaphore.h>
41 #ifdef HAVE_SYS_TIME_H
44 #include <sys/types.h>
50 #ifdef HAVE_SYS_SOCKET_H
51 #include <sys/socket.h>
53 #include <mono/utils/mono-poll.h>
55 #include <sys/epoll.h>
58 #ifndef DISABLE_SOCKETS
59 #include "mono/io-layer/socket-wrappers.h"
62 #include "threadpool.h"
64 #define THREAD_WANTS_A_BREAK(t) ((t->state & (ThreadState_StopRequested | \
65 ThreadState_SuspendRequested)) != 0)
67 #define SPIN_TRYLOCK(i) (InterlockedCompareExchange (&(i), 1, 0) == 0)
68 #define SPIN_LOCK(i) do { \
69 if (SPIN_TRYLOCK (i)) \
73 #define SPIN_UNLOCK(i) i = 0
75 #define EPOLL_DEBUG(...)
76 #define EPOLL_DEBUG_STMT(...)
78 #define TP_DEBUG_STMT(...)
80 /* DEBUG: prints tp data every 2s */
84 #define EPOLL_DEBUG(...) g_message(__VA_ARGS__)
85 #define EPOLL_DEBUG_STMT(...) do { __VA_ARGS__ } while (0)
86 #define TP_DEBUG(...) g_message(__VA_ARGS__)
87 #define TP_DEBUG_STMT(...) do { __VA_ARGS__ } while (0)
90 /* map of CounterSample.cs */
91 struct _MonoCounterSample {
94 gint64 counterFrequency;
95 gint64 systemFrequency;
97 gint64 timeStamp100nSec;
98 gint64 counterTimeStamp;
102 /* mono_thread_pool_init called */
103 static volatile int tp_inited;
106 CRITICAL_SECTION io_lock; /* access to sock_to_state */
107 int inited; // 0 -> not initialized , 1->initializing, 2->initialized, 3->cleaned up
109 MonoGHashTable *sock_to_state;
111 HANDLE new_sem; /* access to newpfd and write side of the pipe */
113 gboolean epoll_disabled;
119 static SocketIOData socket_io_data;
121 /* Keep in sync with the System.MonoAsyncCall class which provides GC tracking */
124 MonoMethodMessage *msg;
125 MonoMethod *cb_method;
126 MonoDelegate *cb_target;
134 MonoMList *first; /* GC root */
136 MonoMList *unused; /* Up to 20 chunks. GC root */
140 volatile gint waiting; /* threads waiting for a work item */
143 volatile gint pool_status; /* 0 -> not initialized, 1 -> initialized, 2 -> cleaning up */
144 /* min, max, n and busy -> Interlocked */
145 volatile gint min_threads;
146 volatile gint max_threads;
147 volatile gint nthreads;
148 volatile gint busy_threads;
150 void (*async_invoke) (gpointer data);
151 void *pc_nitems; /* Performance counter for total number of items in added */
152 void *pc_nthreads; /* Performance counter for total number of active threads */
154 volatile gint destroy_thread;
155 volatile gint ignore_times; /* Used when there's a thread being created or destroyed */
156 volatile gint sp_lock; /* spin lock used to protect ignore_times */
157 volatile gint64 last_check;
158 volatile gint64 time_sum;
162 //TP_DEBUG_ONLY (gint nodes_created);
163 //TP_DEBUG_ONLY (gint nodes_reused);
167 static ThreadPool async_tp;
168 static ThreadPool async_io_tp;
170 static void async_invoke_thread (gpointer data);
171 static MonoObject *mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares);
172 static void threadpool_free_queue (ThreadPool *tp);
173 static void threadpool_append_job (ThreadPool *tp, MonoObject *ar);
174 static void threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs);
175 static void threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer));
176 static void threadpool_start_idle_threads (ThreadPool *tp);
177 static void threadpool_kill_idle_threads (ThreadPool *tp);
178 static gboolean threadpool_start_thread (ThreadPool *tp);
179 static void monitor_thread (gpointer data);
181 static MonoClass *async_call_klass;
182 static MonoClass *socket_async_call_klass;
183 static MonoClass *process_async_call_klass;
185 static GPtrArray *wsqs;
186 CRITICAL_SECTION wsqs_lock;
189 static MonoThreadPoolFunc tp_start_func;
190 static MonoThreadPoolFunc tp_finish_func;
191 static gpointer tp_hooks_user_data;
192 static MonoThreadPoolItemFunc tp_item_begin_func;
193 static MonoThreadPoolItemFunc tp_item_end_func;
194 static gpointer tp_item_user_data;
196 #define INIT_POLLFD(a, b, c) {(a)->fd = b; (a)->events = c; (a)->revents = 0;}
205 AIO_OP_RECV_JUST_CALLBACK,
206 AIO_OP_SEND_JUST_CALLBACK,
210 AIO_OP_ACCEPTRECEIVE,
211 AIO_OP_RECEIVE_BUFFERS,
217 * Functions to check whenever a class is given system class. We need to cache things in MonoDomain since some of the
218 * assemblies can be unloaded.
222 is_system_type (MonoDomain *domain, MonoClass *klass)
224 if (domain->system_image == NULL)
225 domain->system_image = mono_image_loaded ("System");
227 return klass->image == domain->system_image;
231 is_corlib_type (MonoDomain *domain, MonoClass *klass)
233 return klass->image == mono_defaults.corlib;
237 * Note that we call it is_socket_type() where 'socket' refers to the image
238 * that contains the System.Net.Sockets.Socket type.
239 * For moonlight there is a System.Net.Sockets.Socket class in both System.dll and System.Net.dll.
242 is_socket_type (MonoDomain *domain, MonoClass *klass)
244 static const char *version = NULL;
245 static gboolean moonlight;
247 if (is_system_type (domain, klass))
250 /* If moonlight, check if the type is in System.Net.dll too */
251 if (version == NULL) {
252 version = mono_get_runtime_info ()->framework_version;
253 moonlight = !strcmp (version, "2.1");
259 if (domain->system_net_dll == NULL)
260 domain->system_net_dll = mono_image_loaded ("System.Net");
262 return klass->image == domain->system_net_dll;
265 #define check_type_cached(domain, ASSEMBLY, _class, _namespace, _name, loc) do { \
267 return *loc == _class; \
268 if (is_##ASSEMBLY##_type (domain, _class) && !strcmp (_name, _class->name) && !strcmp (_namespace, _class->name_space)) { \
275 #define check_corlib_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, corlib, _class, _namespace, _name, loc)
277 #define check_socket_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, socket, _class, _namespace, _name, loc)
279 #define check_system_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, system, _class, _namespace, _name, loc)
282 is_corlib_asyncresult (MonoDomain *domain, MonoClass *klass)
284 check_corlib_type_cached (domain, klass, "System.Runtime.Remoting.Messaging", "AsyncResult", &domain->corlib_asyncresult_class);
288 is_socket (MonoDomain *domain, MonoClass *klass)
290 check_socket_type_cached (domain, klass, "System.Net.Sockets", "Socket", &domain->socket_class);
294 is_socketasyncresult (MonoDomain *domain, MonoClass *klass)
296 return (klass->nested_in &&
297 is_socket (domain, klass->nested_in) &&
298 !strcmp (klass->name, "SocketAsyncResult"));
302 is_socketasynccall (MonoDomain *domain, MonoClass *klass)
304 return (klass->nested_in &&
305 is_socket (domain, klass->nested_in) &&
306 !strcmp (klass->name, "SocketAsyncCall"));
310 is_appdomainunloaded_exception (MonoDomain *domain, MonoClass *klass)
312 check_corlib_type_cached (domain, klass, "System", "AppDomainUnloadedException", &domain->ad_unloaded_ex_class);
316 is_sd_process (MonoDomain *domain, MonoClass *klass)
318 check_system_type_cached (domain, klass, "System.Diagnostics", "Process", &domain->process_class);
322 is_sdp_asyncreadhandler (MonoDomain *domain, MonoClass *klass)
325 return (klass->nested_in &&
326 is_sd_process (domain, klass->nested_in) &&
327 !strcmp (klass->name, "AsyncReadHandler"));
331 #ifdef DISABLE_SOCKETS
333 #define socket_io_cleanup(x)
336 get_event_from_state (MonoSocketAsyncResult *state)
338 g_assert_not_reached ();
343 get_events_from_list (MonoMList *list)
351 socket_io_cleanup (SocketIOData *data)
353 EnterCriticalSection (&data->io_lock);
354 if (data->inited != 2) {
355 LeaveCriticalSection (&data->io_lock);
361 closesocket (data->pipe [0]);
362 closesocket (data->pipe [1]);
364 if (data->pipe [0] > -1)
365 close (data->pipe [0]);
366 if (data->pipe [1] > -1)
367 close (data->pipe [1]);
372 CloseHandle (data->new_sem);
373 data->new_sem = NULL;
374 mono_g_hash_table_destroy (data->sock_to_state);
375 data->sock_to_state = NULL;
376 g_free (data->newpfd);
379 if (FALSE == data->epoll_disabled)
380 close (data->epollfd);
382 LeaveCriticalSection (&data->io_lock);
386 get_event_from_state (MonoSocketAsyncResult *state)
388 switch (state->operation) {
391 case AIO_OP_RECV_JUST_CALLBACK:
392 case AIO_OP_RECEIVEFROM:
393 case AIO_OP_READPIPE:
394 case AIO_OP_ACCEPTRECEIVE:
395 case AIO_OP_RECEIVE_BUFFERS:
398 case AIO_OP_SEND_JUST_CALLBACK:
401 case AIO_OP_SEND_BUFFERS:
402 case AIO_OP_DISCONNECT:
404 default: /* Should never happen */
405 g_message ("get_event_from_state: unknown value in switch!!!");
411 get_events_from_list (MonoMList *list)
413 MonoSocketAsyncResult *state;
416 while (list && (state = (MonoSocketAsyncResult *)mono_mlist_get_data (list))) {
417 events |= get_event_from_state (state);
418 list = mono_mlist_next (list);
424 #define ICALL_RECV(x) ves_icall_System_Net_Sockets_Socket_Receive_internal (\
425 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
426 x->socket_flags, &x->error);
428 #define ICALL_SEND(x) ves_icall_System_Net_Sockets_Socket_Send_internal (\
429 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
430 x->socket_flags, &x->error);
432 #endif /* !DISABLE_SOCKETS */
435 threadpool_jobs_inc (MonoObject *obj)
438 InterlockedIncrement (&obj->vtable->domain->threadpool_jobs);
442 threadpool_jobs_dec (MonoObject *obj)
444 MonoDomain *domain = obj->vtable->domain;
445 int remaining_jobs = InterlockedDecrement (&domain->threadpool_jobs);
446 if (remaining_jobs == 0 && domain->cleanup_semaphore) {
447 ReleaseSemaphore (domain->cleanup_semaphore, 1, NULL);
455 get_io_event (MonoMList **list, gint event)
465 state = mono_mlist_get_data (current);
466 if (get_event_from_state ((MonoSocketAsyncResult *) state) == event)
471 current = mono_mlist_next (current);
476 mono_mlist_set_next (prev, mono_mlist_next (current));
478 *list = mono_mlist_next (*list);
487 process_io_event (MonoMList *list, int event)
489 MonoSocketAsyncResult *state;
495 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
496 if (get_event_from_state (state) == event)
499 list = mono_mlist_next (list);
503 oldlist = mono_mlist_remove_item (oldlist, list);
504 EPOLL_DEBUG ("Dispatching event %d on socket %p", event, state->handle);
505 threadpool_append_job (&async_io_tp, (MonoObject *) state);
512 mark_bad_fds (mono_pollfd *pfds, int nfds)
518 for (i = 0; i < nfds; i++) {
523 ret = mono_poll (pfd, 1, 0);
524 if (ret == -1 && errno == EBADF) {
525 pfd->revents |= MONO_POLLNVAL;
527 } else if (ret == 1) {
536 socket_io_poll_main (gpointer p)
538 #if MONO_SMALL_CONFIG
539 #define INITIAL_POLLFD_SIZE 128
541 #define INITIAL_POLLFD_SIZE 1024
543 #define POLL_ERRORS (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL)
544 SocketIOData *data = p;
549 MonoInternalThread *thread;
551 thread = mono_thread_internal_current ();
553 allocated = INITIAL_POLLFD_SIZE;
554 pfds = g_new0 (mono_pollfd, allocated);
555 INIT_POLLFD (pfds, data->pipe [0], MONO_POLLIN);
556 for (i = 1; i < allocated; i++)
557 INIT_POLLFD (&pfds [i], -1, 0);
567 if (THREAD_WANTS_A_BREAK (thread))
568 mono_thread_interruption_checkpoint ();
571 nsock = mono_poll (pfds, maxfd, -1);
572 } while (nsock == -1 && errno == EINTR);
575 * Apart from EINTR, we only check EBADF, for the rest:
576 * EINVAL: mono_poll() 'protects' us from descriptor
577 * numbers above the limit if using select() by marking
578 * then as MONO_POLLERR. If a system poll() is being
579 * used, the number of descriptor we're passing will not
580 * be over sysconf(_SC_OPEN_MAX), as the error would have
581 * happened when opening.
583 * EFAULT: we own the memory pointed by pfds.
584 * ENOMEM: we're doomed anyway
588 if (nsock == -1 && errno == EBADF) {
589 pfds->revents = 0; /* Just in case... */
590 nsock = mark_bad_fds (pfds, maxfd);
593 if ((pfds->revents & POLL_ERRORS) != 0) {
594 /* We're supposed to die now, as the pipe has been closed */
596 socket_io_cleanup (data);
600 /* Got a new socket */
601 if ((pfds->revents & MONO_POLLIN) != 0) {
604 for (i = 1; i < allocated; i++) {
606 if (pfd->fd == -1 || data->newpfd == NULL ||
607 pfd->fd == data->newpfd->fd)
611 if (i == allocated) {
616 allocated = allocated * 2;
617 pfds = g_renew (mono_pollfd, oldfd, allocated);
619 for (; i < allocated; i++)
620 INIT_POLLFD (&pfds [i], -1, 0);
623 nread = read (data->pipe [0], one, 1);
625 nread = recv ((SOCKET) data->pipe [0], one, 1, 0);
629 return; /* we're closed */
632 INIT_POLLFD (&pfds [i], data->newpfd->fd, data->newpfd->events);
633 ReleaseSemaphore (data->new_sem, 1, NULL);
642 EnterCriticalSection (&data->io_lock);
643 if (data->inited == 3) {
645 LeaveCriticalSection (&data->io_lock);
646 return; /* cleanup called */
649 for (i = 1; i < maxfd && nsock > 0; i++) {
651 if (pfd->fd == -1 || pfd->revents == 0)
655 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
656 if (list != NULL && (pfd->revents & (MONO_POLLIN | POLL_ERRORS)) != 0) {
657 list = process_io_event (list, MONO_POLLIN);
660 if (list != NULL && (pfd->revents & (MONO_POLLOUT | POLL_ERRORS)) != 0) {
661 list = process_io_event (list, MONO_POLLOUT);
665 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (pfd->fd), list);
666 pfd->events = get_events_from_list (list);
668 mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
674 LeaveCriticalSection (&data->io_lock);
679 #define EPOLL_ERRORS (EPOLLERR | EPOLLHUP)
680 #define EPOLL_NEVENTS 128
682 socket_io_epoll_main (gpointer p)
686 MonoInternalThread *thread;
687 struct epoll_event *events, *evt;
689 gpointer async_results [EPOLL_NEVENTS * 2]; // * 2 because each loop can add up to 2 results here
693 epollfd = data->epollfd;
694 thread = mono_thread_internal_current ();
695 events = g_new0 (struct epoll_event, EPOLL_NEVENTS);
700 if (THREAD_WANTS_A_BREAK (thread))
701 mono_thread_interruption_checkpoint ();
703 EPOLL_DEBUG ("epoll_wait init");
704 ready = epoll_wait (epollfd, events, EPOLL_NEVENTS, -1);
707 EPOLL_DEBUG ("epoll_wait end with %d ready sockets (%d %s).", ready, err, (ready == -1) ? g_strerror (err) : "");
710 } while (ready == -1 && errno == EINTR);
716 g_warning ("epoll_wait: %d %s", err, g_strerror (err));
722 EnterCriticalSection (&data->io_lock);
723 if (data->inited == 3) {
726 LeaveCriticalSection (&data->io_lock);
727 return; /* cleanup called */
731 for (i = 0; i < ready; i++) {
738 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
739 EPOLL_DEBUG ("Event %d on %d list length: %d", evt->events, fd, mono_mlist_length (list));
740 if (list != NULL && (evt->events & (EPOLLIN | EPOLL_ERRORS)) != 0) {
741 ares = get_io_event (&list, MONO_POLLIN);
743 async_results [nresults++] = ares;
746 if (list != NULL && (evt->events & (EPOLLOUT | EPOLL_ERRORS)) != 0) {
747 ares = get_io_event (&list, MONO_POLLOUT);
749 async_results [nresults++] = ares;
753 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (fd), list);
754 evt->events = get_events_from_list (list);
755 EPOLL_DEBUG ("MOD %d to %d", fd, evt->events);
756 if (epoll_ctl (epollfd, EPOLL_CTL_MOD, fd, evt)) {
757 if (epoll_ctl (epollfd, EPOLL_CTL_ADD, fd, evt) == -1) {
760 EPOLL_DEBUG ("epoll_ctl(MOD): %d %s fd: %d events: %d", err, g_strerror (err), fd, evt->events);
766 mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (fd));
767 EPOLL_DEBUG ("DEL %d", fd);
768 epoll_ctl (epollfd, EPOLL_CTL_DEL, fd, evt);
771 LeaveCriticalSection (&data->io_lock);
772 threadpool_append_jobs (&async_io_tp, (MonoObject **) async_results, nresults);
773 memset (async_results, 0, sizeof (gpointer) * nresults);
780 * select/poll wake up when a socket is closed, but epoll just removes
781 * the socket from its internal list without notification.
784 mono_thread_pool_remove_socket (int sock)
786 MonoMList *list, *next;
787 MonoSocketAsyncResult *state;
789 if (socket_io_data.inited == 0)
792 EnterCriticalSection (&socket_io_data.io_lock);
793 if (socket_io_data.sock_to_state == NULL) {
794 LeaveCriticalSection (&socket_io_data.io_lock);
797 list = mono_g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
799 mono_g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
800 LeaveCriticalSection (&socket_io_data.io_lock);
803 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
804 if (state->operation == AIO_OP_RECEIVE)
805 state->operation = AIO_OP_RECV_JUST_CALLBACK;
806 else if (state->operation == AIO_OP_SEND)
807 state->operation = AIO_OP_SEND_JUST_CALLBACK;
809 next = mono_mlist_remove_item (list, list);
810 list = process_io_event (list, MONO_POLLIN);
812 process_io_event (list, MONO_POLLOUT);
820 connect_hack (gpointer x)
822 struct sockaddr_in *addr = (struct sockaddr_in *) x;
825 while (connect ((SOCKET) socket_io_data.pipe [1], (SOCKADDR *) addr, sizeof (struct sockaddr_in))) {
828 g_warning ("Error initializing async. sockets %d.", WSAGetLastError ());
829 g_assert (WSAGetLastError ());
836 socket_io_init (SocketIOData *data)
839 struct sockaddr_in server;
840 struct sockaddr_in client;
847 if (data->inited >= 2) // 2 -> initialized, 3-> cleaned up
850 inited = InterlockedCompareExchange (&data->inited, 1, 0);
853 if (data->inited >= 2)
859 EnterCriticalSection (&data->io_lock);
862 data->epoll_disabled = (g_getenv ("MONO_DISABLE_AIO") != NULL);
863 if (FALSE == data->epoll_disabled) {
864 data->epollfd = epoll_create (256);
865 data->epoll_disabled = (data->epollfd == -1);
866 if (data->epoll_disabled && g_getenv ("MONO_DEBUG"))
867 g_message ("epoll_create() failed. Using plain poll().");
872 data->epoll_disabled = TRUE;
876 if (data->epoll_disabled) {
877 if (pipe (data->pipe) != 0) {
887 srv = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
888 g_assert (srv != INVALID_SOCKET);
889 data->pipe [1] = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
890 g_assert (data->pipe [1] != INVALID_SOCKET);
892 server.sin_family = AF_INET;
893 server.sin_addr.s_addr = inet_addr ("127.0.0.1");
895 if (bind (srv, (SOCKADDR *) &server, sizeof (server))) {
896 g_print ("%d\n", WSAGetLastError ());
900 len = sizeof (server);
901 getsockname (srv, (SOCKADDR *) &server, &len);
903 mono_thread_create (mono_get_root_domain (), connect_hack, &server);
904 len = sizeof (server);
905 data->pipe [0] = accept (srv, (SOCKADDR *) &client, &len);
906 g_assert (data->pipe [0] != INVALID_SOCKET);
909 data->sock_to_state = mono_g_hash_table_new_type (g_direct_hash, g_direct_equal, MONO_HASH_VALUE_GC);
911 if (data->epoll_disabled) {
912 data->new_sem = CreateSemaphore (NULL, 1, 1, NULL);
913 g_assert (data->new_sem != NULL);
916 stack_size = mono_threads_get_default_stacksize ();
917 /* 128k stacks could lead to problems on 64 bit systems with large pagesizes+altstack */
918 mono_threads_set_default_stacksize (128 * (sizeof (gpointer) / 4) * 1024);
919 if (data->epoll_disabled) {
920 mono_thread_create_internal (mono_get_root_domain (), socket_io_poll_main, data, TRUE);
924 mono_thread_create_internal (mono_get_root_domain (), socket_io_epoll_main, data, TRUE);
927 mono_threads_set_default_stacksize (stack_size);
928 LeaveCriticalSection (&data->io_lock);
933 socket_io_add_poll (MonoSocketAsyncResult *state)
938 SocketIOData *data = &socket_io_data;
941 if (mono_runtime_is_shutting_down () || data->inited == 3 || data->sock_to_state == NULL)
944 #if defined(PLATFORM_MACOSX) || defined(PLATFORM_BSD) || defined(HOST_WIN32) || defined(PLATFORM_SOLARIS)
945 /* select() for connect() does not work well on the Mac. Bug #75436. */
946 /* Bug #77637 for the BSD 6 case */
947 /* Bug #78888 for the Windows case */
948 if (state->operation == AIO_OP_CONNECT && state->blocking == TRUE) {
949 //FIXME: increment number of threads while this one is waiting?
950 threadpool_append_job (&async_io_tp, (MonoObject *) state);
954 WaitForSingleObject (data->new_sem, INFINITE);
955 if (data->newpfd == NULL)
956 data->newpfd = g_new0 (mono_pollfd, 1);
958 EnterCriticalSection (&data->io_lock);
959 if (data->sock_to_state == NULL) {
960 LeaveCriticalSection (&data->io_lock);
964 /* FIXME: 64 bit issue: handle can be a pointer on windows? */
965 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (state->handle));
967 list = mono_mlist_alloc ((MonoObject*)state);
969 list = mono_mlist_append (list, (MonoObject*)state);
972 events = get_events_from_list (list);
973 INIT_POLLFD (data->newpfd, GPOINTER_TO_INT (state->handle), events);
974 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (state->handle), list);
975 LeaveCriticalSection (&data->io_lock);
976 *msg = (char) state->operation;
978 w = write (data->pipe [1], msg, 1);
981 send ((SOCKET) data->pipe [1], msg, 1, 0);
987 socket_io_add_epoll (MonoSocketAsyncResult *state)
990 SocketIOData *data = &socket_io_data;
991 struct epoll_event event;
995 if (mono_runtime_is_shutting_down () || data->inited == 3 || data->sock_to_state == NULL)
998 memset (&event, 0, sizeof (struct epoll_event));
999 fd = GPOINTER_TO_INT (state->handle);
1000 EnterCriticalSection (&data->io_lock);
1001 if (data->sock_to_state == NULL) {
1002 LeaveCriticalSection (&data->io_lock);
1005 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
1007 list = mono_mlist_alloc ((MonoObject*)state);
1008 epoll_op = EPOLL_CTL_ADD;
1010 list = mono_mlist_append (list, (MonoObject*)state);
1011 epoll_op = EPOLL_CTL_MOD;
1014 ievt = get_events_from_list (list);
1015 if ((ievt & MONO_POLLIN) != 0)
1016 event.events |= EPOLLIN;
1017 if ((ievt & MONO_POLLOUT) != 0)
1018 event.events |= EPOLLOUT;
1020 mono_g_hash_table_replace (data->sock_to_state, state->handle, list);
1022 EPOLL_DEBUG ("%s %d with %d", epoll_op == EPOLL_CTL_ADD ? "ADD" : "MOD", fd, event.events);
1023 if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
1025 if (epoll_op == EPOLL_CTL_ADD && err == EEXIST) {
1026 epoll_op = EPOLL_CTL_MOD;
1027 if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
1028 g_message ("epoll_ctl(MOD): %d %s", err, g_strerror (err));
1032 LeaveCriticalSection (&data->io_lock);
1039 socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
1041 if (async_tp.pool_status == 2 || mono_runtime_is_shutting_down ())
1044 socket_io_init (&socket_io_data);
1046 MONO_OBJECT_SETREF (state, ares, ares);
1048 if (socket_io_data.epoll_disabled == FALSE) {
1049 if (socket_io_add_epoll (state))
1053 socket_io_add_poll (state);
1056 #ifndef DISABLE_SOCKETS
1058 socket_io_filter (MonoObject *target, MonoObject *state)
1061 MonoSocketAsyncResult *sock_res;
1065 if (target == NULL || state == NULL)
1068 domain = target->vtable->domain;
1069 klass = target->vtable->klass;
1070 if (socket_async_call_klass == NULL && is_socketasynccall (domain, klass))
1071 socket_async_call_klass = klass;
1073 if (process_async_call_klass == NULL && is_sdp_asyncreadhandler (domain, klass))
1074 process_async_call_klass = klass;
1076 if (klass != socket_async_call_klass && klass != process_async_call_klass)
1079 sock_res = (MonoSocketAsyncResult *) state;
1080 op = sock_res->operation;
1081 if (op < AIO_OP_FIRST || op >= AIO_OP_LAST)
1086 #endif /* !DISABLE_SOCKETS */
1088 /* Returns the exception thrown when invoking, if any */
1090 mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares)
1092 ASyncCall *ac = (ASyncCall *)ares->object_data;
1093 MonoObject *res, *exc = NULL;
1094 MonoArray *out_args = NULL;
1095 HANDLE wait_event = NULL;
1097 if (ares->execution_context) {
1098 /* use captured ExecutionContext (if available) */
1099 MONO_OBJECT_SETREF (ares, original_context, mono_thread_get_execution_context ());
1100 mono_thread_set_execution_context (ares->execution_context);
1102 ares->original_context = NULL;
1106 /* Fast path from ThreadPool.*QueueUserWorkItem */
1107 void *pa = ares->async_state;
1108 mono_runtime_delegate_invoke (ares->async_delegate, &pa, &exc);
1110 MonoObject *cb_exc = NULL;
1112 ac->msg->exc = NULL;
1113 res = mono_message_invoke (ares->async_delegate, ac->msg, &exc, &out_args);
1114 MONO_OBJECT_SETREF (ac, res, res);
1115 MONO_OBJECT_SETREF (ac, msg->exc, exc);
1116 MONO_OBJECT_SETREF (ac, out_args, out_args);
1118 mono_monitor_enter ((MonoObject *) ares);
1119 ares->completed = 1;
1120 if (ares->handle != NULL)
1121 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
1122 mono_monitor_exit ((MonoObject *) ares);
1123 /* notify listeners */
1124 if (wait_event != NULL)
1125 SetEvent (wait_event);
1127 /* call async callback if cb_method != null*/
1128 if (ac != NULL && ac->cb_method) {
1131 mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &cb_exc);
1132 MONO_OBJECT_SETREF (ac->msg, exc, cb_exc);
1139 /* restore original thread execution context if flow isn't suppressed, i.e. non null */
1140 if (ares->original_context) {
1141 mono_thread_set_execution_context (ares->original_context);
1142 ares->original_context = NULL;
1148 threadpool_start_idle_threads (ThreadPool *tp)
1152 if (tp->pool_status == 1 && !tp->is_io)
1153 mono_thread_create_internal (mono_get_root_domain (), monitor_thread, tp, TRUE);
1157 if (n >= tp->min_threads)
1159 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n)
1162 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
1163 mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE);
1164 SleepEx (100, TRUE);
1169 threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer))
1171 memset (tp, 0, sizeof (ThreadPool));
1172 MONO_SEM_INIT (&tp->lock, 1);
1173 tp->min_threads = min_threads;
1174 tp->max_threads = max_threads;
1175 tp->async_invoke = async_invoke;
1176 MONO_SEM_INIT (&tp->new_job, 0);
1180 init_perf_counter (const char *category, const char *counter)
1182 MonoString *category_str;
1183 MonoString *counter_str;
1184 MonoString *machine;
1189 if (category == NULL || counter == NULL)
1191 root = mono_get_root_domain ();
1192 category_str = mono_string_new (root, category);
1193 counter_str = mono_string_new (root, counter);
1194 machine = mono_string_new (root, ".");
1195 return mono_perfcounter_get_impl (category_str, counter_str, NULL, machine, &type, &custom);
1200 print_pool_info (ThreadPool *tp)
1203 // if (tp->tail - tp->head == 0)
1206 g_print ("Pool status? %d\n", InterlockedCompareExchange (&tp->pool_status, 0, 0));
1207 g_print ("Min. threads: %d\n", InterlockedCompareExchange (&tp->min_threads, 0, 0));
1208 g_print ("Max. threads: %d\n", InterlockedCompareExchange (&tp->max_threads, 0, 0));
1209 g_print ("nthreads: %d\n", InterlockedCompareExchange (&tp->nthreads, 0, 0));
1210 g_print ("busy threads: %d\n", InterlockedCompareExchange (&tp->busy_threads, 0, 0));
1211 g_print ("Waiting: %d\n", InterlockedCompareExchange (&tp->waiting, 0, 0));
1212 g_print ("Queued: %d\n", (tp->tail - tp->head));
1213 if (tp == &async_tp) {
1215 EnterCriticalSection (&wsqs_lock);
1216 for (i = 0; i < wsqs->len; i++) {
1217 g_print ("\tWSQ %d: %d\n", i, mono_wsq_count (g_ptr_array_index (wsqs, i)));
1219 LeaveCriticalSection (&wsqs_lock);
1221 g_print ("\tSockets: %d\n", mono_g_hash_table_size (socket_io_data.sock_to_state));
1223 g_print ("-------------\n");
1227 signal_handler (int signo)
1232 MONO_SEM_WAIT (&tp->lock);
1233 g_print ("\n-----Non-IO-----\n");
1234 print_pool_info (tp);
1235 MONO_SEM_POST (&tp->lock);
1237 MONO_SEM_WAIT (&tp->lock);
1238 g_print ("\n-----IO-----\n");
1239 print_pool_info (tp);
1240 MONO_SEM_POST (&tp->lock);
1246 monitor_thread (gpointer data)
1249 MonoInternalThread *thread;
1255 thread = mono_thread_internal_current ();
1260 ts = mono_msec_ticks ();
1261 if (SleepEx (ms, TRUE) == 0)
1263 ms -= (mono_msec_ticks () - ts);
1264 if (mono_runtime_is_shutting_down ())
1266 if (THREAD_WANTS_A_BREAK (thread))
1267 mono_thread_interruption_checkpoint ();
1270 if (mono_runtime_is_shutting_down ())
1272 if (tp->waiting > 0)
1274 MONO_SEM_WAIT (&tp->lock);
1275 need_one = (tp->head != tp->tail);
1277 EnterCriticalSection (&wsqs_lock);
1278 for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
1280 wsq = g_ptr_array_index (wsqs, i);
1281 if (mono_wsq_count (wsq) > 0) {
1286 LeaveCriticalSection (&wsqs_lock);
1288 MONO_SEM_POST (&tp->lock);
1290 threadpool_start_thread (tp);
1295 mono_thread_pool_init ()
1297 gint threads_per_cpu = 1;
1299 gint cpu_count = mono_cpu_count ();
1305 result = InterlockedCompareExchange (&tp_inited, 1, 0);
1314 MONO_GC_REGISTER_ROOT_SINGLE (async_tp.first);
1315 MONO_GC_REGISTER_ROOT_SINGLE (async_tp.last);
1316 MONO_GC_REGISTER_ROOT_SINGLE (async_tp.unused);
1317 MONO_GC_REGISTER_ROOT_SINGLE (async_io_tp.first);
1318 MONO_GC_REGISTER_ROOT_SINGLE (async_io_tp.unused);
1319 MONO_GC_REGISTER_ROOT_SINGLE (async_io_tp.last);
1321 MONO_GC_REGISTER_ROOT_FIXED (socket_io_data.sock_to_state);
1322 InitializeCriticalSection (&socket_io_data.io_lock);
1323 if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
1324 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
1325 if (threads_per_cpu < 1)
1326 threads_per_cpu = 1;
1329 thread_count = MIN (cpu_count * threads_per_cpu, 100 * cpu_count);
1330 threadpool_init (&async_tp, thread_count, MAX (100 * cpu_count, thread_count), async_invoke_thread);
1331 threadpool_init (&async_io_tp, cpu_count * 2, cpu_count * 4, async_invoke_thread);
1332 async_io_tp.is_io = TRUE;
1334 async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
1335 g_assert (async_call_klass);
1337 InitializeCriticalSection (&wsqs_lock);
1338 wsqs = g_ptr_array_sized_new (MAX (100 * cpu_count, thread_count));
1341 async_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "Work Items Added");
1342 g_assert (async_tp.pc_nitems);
1344 async_io_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "IO Work Items Added");
1345 g_assert (async_io_tp.pc_nitems);
1347 async_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of Threads");
1348 g_assert (async_tp.pc_nthreads);
1350 async_io_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of IO Threads");
1351 g_assert (async_io_tp.pc_nthreads);
1354 signal (SIGALRM, signal_handler);
1359 static MonoAsyncResult *
1360 create_simple_asyncresult (MonoObject *target, MonoObject *state)
1362 MonoDomain *domain = mono_domain_get ();
1363 MonoAsyncResult *ares;
1365 /* Don't call mono_async_result_new() to avoid capturing the context */
1366 ares = (MonoAsyncResult *) mono_object_new (domain, mono_defaults.asyncresult_class);
1367 MONO_OBJECT_SETREF (ares, async_delegate, target);
1368 MONO_OBJECT_SETREF (ares, async_state, state);
1373 icall_append_io_job (MonoObject *target, MonoSocketAsyncResult *state)
1375 MonoAsyncResult *ares;
1377 ares = create_simple_asyncresult (target, (MonoObject *) state);
1378 socket_io_add (ares, state);
1382 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
1385 MonoDomain *domain = mono_domain_get ();
1386 MonoAsyncResult *ares;
1389 ac = (ASyncCall*)mono_object_new (domain, async_call_klass);
1390 MONO_OBJECT_SETREF (ac, msg, msg);
1391 MONO_OBJECT_SETREF (ac, state, state);
1393 if (async_callback) {
1394 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
1395 MONO_OBJECT_SETREF (ac, cb_target, async_callback);
1398 ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
1399 MONO_OBJECT_SETREF (ares, async_delegate, target);
1401 #ifndef DISABLE_SOCKETS
1402 if (socket_io_filter (target, state)) {
1403 socket_io_add (ares, (MonoSocketAsyncResult *) state);
1407 threadpool_append_job (&async_tp, (MonoObject *) ares);
1412 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1420 /* check if already finished */
1421 mono_monitor_enter ((MonoObject *) ares);
1423 if (ares->endinvoke_called) {
1424 *exc = (MonoObject *) mono_get_exception_invalid_operation (NULL);
1425 mono_monitor_exit ((MonoObject *) ares);
1429 ares->endinvoke_called = 1;
1430 /* wait until we are really finished */
1431 if (!ares->completed) {
1432 if (ares->handle == NULL) {
1433 wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1434 g_assert(wait_event != 0);
1435 MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), wait_event));
1437 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
1439 mono_monitor_exit ((MonoObject *) ares);
1440 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
1442 mono_monitor_exit ((MonoObject *) ares);
1445 ac = (ASyncCall *) ares->object_data;
1446 g_assert (ac != NULL);
1447 *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1448 *out_args = ac->out_args;
1454 threadpool_kill_idle_threads (ThreadPool *tp)
1458 n = (gint) InterlockedCompareExchange (&tp->max_threads, 0, -1);
1461 MONO_SEM_POST (&tp->new_job);
1466 mono_thread_pool_cleanup (void)
1468 if (!(async_tp.pool_status == 0 || async_tp.pool_status == 2)) {
1469 if (!(async_tp.pool_status == 1 && InterlockedCompareExchange (&async_tp.pool_status, 2, 1) == 2)) {
1470 InterlockedExchange (&async_io_tp.pool_status, 2);
1471 MONO_SEM_WAIT (&async_tp.lock);
1472 threadpool_free_queue (&async_tp);
1473 threadpool_kill_idle_threads (&async_tp);
1474 MONO_SEM_POST (&async_tp.lock);
1476 socket_io_cleanup (&socket_io_data); /* Empty when DISABLE_SOCKETS is defined */
1477 MONO_SEM_WAIT (&async_io_tp.lock);
1478 threadpool_free_queue (&async_io_tp);
1479 threadpool_kill_idle_threads (&async_io_tp);
1480 MONO_SEM_POST (&async_io_tp.lock);
1481 MONO_SEM_DESTROY (&async_io_tp.new_job);
1485 EnterCriticalSection (&wsqs_lock);
1486 mono_wsq_cleanup ();
1488 g_ptr_array_free (wsqs, TRUE);
1490 LeaveCriticalSection (&wsqs_lock);
1491 MONO_SEM_DESTROY (&async_tp.new_job);
1494 /* Caller must enter &tp->lock */
1496 dequeue_job_nolock (ThreadPool *tp)
1504 if (mono_runtime_is_shutting_down ())
1506 if (!list || tp->head == tp->tail)
1509 array = (MonoArray *) mono_mlist_get_data (list);
1510 ar = mono_array_get (array, MonoObject *, tp->head % QUEUE_LENGTH);
1511 mono_array_set (array, MonoObject *, tp->head % QUEUE_LENGTH, NULL);
1513 if ((tp->head % QUEUE_LENGTH) == 0) {
1515 tp->first = mono_mlist_next (list);
1516 if (tp->first == NULL)
1518 if (mono_mlist_length (tp->unused) < 20) {
1519 /* reuse this chunk */
1520 tp->unused = mono_mlist_set_next (list, tp->unused);
1522 tp->head -= QUEUE_LENGTH;
1523 tp->tail -= QUEUE_LENGTH;
1526 } while (ar == NULL);
1531 threadpool_start_thread (ThreadPool *tp)
1535 while (!mono_runtime_is_shutting_down () && (n = tp->nthreads) < tp->max_threads) {
1536 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n) {
1537 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
1538 mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE);
1547 pulse_on_new_job (ThreadPool *tp)
1550 MONO_SEM_POST (&tp->new_job);
1554 icall_append_job (MonoObject *ar)
1556 threadpool_append_job (&async_tp, ar);
1560 threadpool_append_job (ThreadPool *tp, MonoObject *ar)
1562 threadpool_append_jobs (tp, &ar, 1);
1566 create_or_reuse_list (ThreadPool *tp)
1574 tp->unused = mono_mlist_next (list);
1575 mono_mlist_set_next (list, NULL);
1576 //TP_DEBUG (tp->nodes_reused++);
1578 array = mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, QUEUE_LENGTH);
1579 list = mono_mlist_alloc ((MonoObject *) array);
1580 //TP_DEBUG (tp->nodes_created++);
1586 threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs)
1588 static int job_counter;
1593 gboolean lock_taken = FALSE; /* We won't take the lock when the local queue is used */
1595 if (mono_runtime_is_shutting_down ())
1598 if (tp->pool_status == 0 && InterlockedCompareExchange (&tp->pool_status, 1, 0) == 0)
1599 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, tp, TRUE);
1601 for (i = 0; i < njobs; i++) {
1603 if (ar == NULL || mono_domain_is_unloading (ar->vtable->domain))
1604 continue; /* Might happen when cleaning domain jobs */
1605 if (!tp->is_io && (InterlockedIncrement (&job_counter) % 10) == 0) {
1606 MonoAsyncResult *o = (MonoAsyncResult *) ar;
1607 o->add_time = mono_100ns_ticks ();
1609 threadpool_jobs_inc (ar);
1610 mono_perfcounter_update_value (tp->pc_nitems, TRUE, 1);
1611 if (!tp->is_io && mono_wsq_local_push (ar))
1615 MONO_SEM_WAIT (&tp->lock);
1618 if ((tp->tail % QUEUE_LENGTH) == 0) {
1619 list = create_or_reuse_list (tp);
1620 if (tp->last != NULL)
1621 mono_mlist_set_next (tp->last, list);
1623 if (tp->first == NULL)
1624 tp->first = tp->last;
1627 array = (MonoArray *) mono_mlist_get_data (tp->last);
1628 mono_array_setref (array, tp->tail % QUEUE_LENGTH, ar);
1632 MONO_SEM_POST (&tp->lock);
1634 for (i = 0; i < MIN(njobs, tp->max_threads); i++)
1635 pulse_on_new_job (tp);
1639 threadpool_clear_queue (ThreadPool *tp, MonoDomain *domain)
1648 MONO_SEM_WAIT (&tp->lock);
1649 current = tp->first;
1651 array = (MonoArray *) mono_mlist_get_data (current);
1652 for (i = 0; i < QUEUE_LENGTH; i++) {
1653 obj = mono_array_get (array, MonoObject*, i);
1654 if (obj != NULL && obj->vtable->domain == domain) {
1656 mono_array_setref (array, i, NULL);
1657 threadpool_jobs_dec (obj);
1660 current = mono_mlist_next (current);
1663 if (!domain_count) {
1664 MONO_SEM_POST (&tp->lock);
1668 current = tp->first;
1673 MONO_SEM_POST (&tp->lock);
1674 /* Re-add everything but the nullified elements */
1676 array = (MonoArray *) mono_mlist_get_data (current);
1677 threadpool_append_jobs (tp, mono_array_addr (array, MonoObject *, 0), QUEUE_LENGTH);
1678 memset (mono_array_addr (array, MonoObject *, 0), 0, sizeof (MonoObject *) * QUEUE_LENGTH);
1679 current = mono_mlist_next (current);
1684 * Clean up the threadpool of all domain jobs.
1685 * Can only be called as part of the domain unloading process as
1686 * it will wait for all jobs to be visible to the interruption code.
1689 mono_thread_pool_remove_domain_jobs (MonoDomain *domain, int timeout)
1693 guint32 start_time = 0;
1695 g_assert (domain->state == MONO_APPDOMAIN_UNLOADING);
1697 threadpool_clear_queue (&async_tp, domain);
1698 threadpool_clear_queue (&async_io_tp, domain);
1701 * There might be some threads out that could be about to execute stuff from the given domain.
1702 * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
1704 sem_handle = CreateSemaphore (NULL, 0, 1, NULL);
1706 domain->cleanup_semaphore = sem_handle;
1708 * The memory barrier here is required to have global ordering between assigning to cleanup_semaphone
1709 * and reading threadpool_jobs.
1710 * Otherwise this thread could read a stale version of threadpool_jobs and wait forever.
1712 mono_memory_write_barrier ();
1714 if (domain->threadpool_jobs && timeout != -1)
1715 start_time = mono_msec_ticks ();
1716 while (domain->threadpool_jobs) {
1717 WaitForSingleObject (sem_handle, timeout);
1718 if (timeout != -1 && (mono_msec_ticks () - start_time) > timeout) {
1724 domain->cleanup_semaphore = NULL;
1725 CloseHandle (sem_handle);
1730 threadpool_free_queue (ThreadPool *tp)
1732 tp->head = tp->tail = 0;
1738 mono_thread_pool_is_queue_array (MonoArray *o)
1742 // FIXME: need some fix in sgen code.
1743 // There are roots at: async*tp.unused (MonoMList) and wsqs [n]->queue (MonoArray)
1744 return obj == async_tp.first || obj == async_io_tp.first;
1753 EnterCriticalSection (&wsqs_lock);
1754 wsq = mono_wsq_create ();
1756 LeaveCriticalSection (&wsqs_lock);
1759 for (i = 0; i < wsqs->len; i++) {
1760 if (g_ptr_array_index (wsqs, i) == NULL) {
1761 wsqs->pdata [i] = wsq;
1762 LeaveCriticalSection (&wsqs_lock);
1766 g_ptr_array_add (wsqs, wsq);
1767 LeaveCriticalSection (&wsqs_lock);
1772 remove_wsq (MonoWSQ *wsq)
1779 EnterCriticalSection (&wsqs_lock);
1781 LeaveCriticalSection (&wsqs_lock);
1784 g_ptr_array_remove_fast (wsqs, wsq);
1786 while (mono_wsq_local_pop (&data)) {
1787 threadpool_jobs_dec (data);
1790 mono_wsq_destroy (wsq);
1791 LeaveCriticalSection (&wsqs_lock);
1795 try_steal (gpointer *data, gboolean retry)
1800 if (wsqs == NULL || data == NULL || *data != NULL)
1805 if (mono_runtime_is_shutting_down ())
1807 for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
1808 if (mono_runtime_is_shutting_down ()) {
1811 mono_wsq_try_steal (wsqs->pdata [i], data, ms);
1812 if (*data != NULL) {
1817 } while (retry && ms < 11);
1821 dequeue_or_steal (ThreadPool *tp, gpointer *data)
1823 if (mono_runtime_is_shutting_down ())
1825 TP_DEBUG ("Dequeue");
1826 MONO_SEM_WAIT (&tp->lock);
1827 *data = dequeue_job_nolock (tp);
1828 MONO_SEM_POST (&tp->lock);
1829 if (!tp->is_io && !*data)
1830 try_steal (data, FALSE);
1831 return (*data != NULL);
1835 process_idle_times (ThreadPool *tp, gint64 t)
1839 gboolean compute_avg;
1843 if (tp->ignore_times || t <= 0)
1846 compute_avg = FALSE;
1847 ticks = mono_100ns_ticks ();
1849 SPIN_LOCK (tp->sp_lock);
1850 if (tp->ignore_times) {
1851 SPIN_UNLOCK (tp->sp_lock);
1856 if (tp->last_check == 0)
1857 tp->last_check = ticks;
1858 else if (tp->last_check > 0 && (ticks - tp->last_check) > 5000000) {
1859 tp->ignore_times = 1;
1862 SPIN_UNLOCK (tp->sp_lock);
1867 //printf ("Items: %d Time elapsed: %.3fs\n", tp->n_sum, (ticks - tp->last_check) / 10000.0);
1868 tp->last_check = ticks;
1870 avg = tp->time_sum / tp->n_sum;
1871 if (tp->averages [1] == 0) {
1872 tp->averages [1] = avg;
1874 per1 = ((100 * (ABS (avg - tp->averages [1]))) / tp->averages [1]);
1876 if (avg > tp->averages [1]) {
1877 if (tp->averages [1] < tp->averages [0]) {
1882 } else if (avg < tp->averages [1] && tp->averages [1] < tp->averages [0]) {
1887 min = tp->min_threads;
1889 if ((n - min) < min && tp->busy_threads == n)
1893 if (new_threads != 0) {
1894 printf ("n: %d per1: %lld avg=%lld avg1=%lld avg0=%lld\n", new_threads, per1, avg, tp->averages [1], tp->averages [0]);
1902 tp->averages [0] = tp->averages [1];
1903 tp->averages [1] = avg;
1904 tp->ignore_times = 0;
1906 if (new_threads == -1) {
1907 if (tp->destroy_thread == 0 && InterlockedCompareExchange (&tp->destroy_thread, 1, 0) == 0)
1908 pulse_on_new_job (tp);
1913 should_i_die (ThreadPool *tp)
1915 gboolean result = FALSE;
1916 if (tp->destroy_thread == 1 && InterlockedCompareExchange (&tp->destroy_thread, 0, 1) == 1)
1917 result = (tp->nthreads > tp->min_threads);
1922 async_invoke_thread (gpointer data)
1925 MonoInternalThread *thread;
1935 thread = mono_thread_internal_current ();
1937 mono_profiler_thread_start (thread->tid);
1940 tp_start_func (tp_hooks_user_data);
1944 MonoAsyncResult *ar;
1946 gboolean is_io_task;
1951 ar = (MonoAsyncResult *) data;
1953 InterlockedIncrement (&tp->busy_threads);
1954 domain = ((MonoObject *)ar)->vtable->domain;
1955 #ifndef DISABLE_SOCKET
1956 klass = ((MonoObject *) data)->vtable->klass;
1957 is_io_task = !is_corlib_asyncresult (domain, klass);
1960 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1961 is_socket = is_socketasyncresult (domain, klass);
1963 switch (state->operation) {
1964 case AIO_OP_RECEIVE:
1965 state->total = ICALL_RECV (state);
1968 state->total = ICALL_SEND (state);
1973 /* worker threads invokes methods in different domains,
1974 * so we need to set the right domain here */
1977 if (mono_domain_is_unloading (domain) || mono_runtime_is_shutting_down ()) {
1978 threadpool_jobs_dec ((MonoObject *)ar);
1981 InterlockedDecrement (&tp->busy_threads);
1983 mono_thread_push_appdomain_ref (domain);
1984 if (threadpool_jobs_dec ((MonoObject *)ar)) {
1987 mono_thread_pop_appdomain_ref ();
1988 InterlockedDecrement (&tp->busy_threads);
1992 if (mono_domain_set (domain, FALSE)) {
1995 if (tp_item_begin_func)
1996 tp_item_begin_func (tp_item_user_data);
1998 if (!is_io_task && ar->add_time > 0)
1999 process_idle_times (tp, ar->add_time);
2000 exc = mono_async_invoke (tp, ar);
2001 if (tp_item_end_func)
2002 tp_item_end_func (tp_item_user_data);
2003 if (exc && mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_CURRENT) {
2007 klass = exc->vtable->klass;
2008 unloaded = is_appdomainunloaded_exception (exc->vtable->domain, klass);
2009 if (!unloaded && klass != mono_defaults.threadabortexception_class) {
2010 mono_unhandled_exception (exc);
2014 if (is_socket && tp->is_io) {
2015 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
2017 if (state->completed && state->callback) {
2018 MonoAsyncResult *cb_ares;
2019 cb_ares = create_simple_asyncresult ((MonoObject *) state->callback,
2020 (MonoObject *) state);
2021 icall_append_job ((MonoObject *) cb_ares);
2024 mono_domain_set (mono_get_root_domain (), TRUE);
2026 mono_thread_pop_appdomain_ref ();
2027 InterlockedDecrement (&tp->busy_threads);
2028 /* If the callee changes the background status, set it back to TRUE */
2029 mono_thread_clr_state (thread , ~ThreadState_Background);
2030 if (!mono_thread_test_state (thread , ThreadState_Background))
2031 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
2037 must_die = should_i_die (tp);
2038 TP_DEBUG ("Trying to get a job");
2039 if (!must_die && (tp->is_io || !mono_wsq_local_pop (&data)))
2040 dequeue_or_steal (tp, &data);
2041 TP_DEBUG ("Done trying to get a job %p", data);
2044 while (!must_die && !data && n_naps < 4) {
2047 TP_DEBUG ("Waiting");
2048 InterlockedIncrement (&tp->waiting);
2049 #if defined(__OpenBSD__)
2050 while ((res = mono_sem_wait (&tp->new_job, TRUE)) == -1) {// && errno == EINTR) {
2052 while ((res = mono_sem_timedwait (&tp->new_job, 2000, TRUE)) == -1) {// && errno == EINTR) {
2054 if (mono_runtime_is_shutting_down ())
2056 if (THREAD_WANTS_A_BREAK (thread))
2057 mono_thread_interruption_checkpoint ();
2059 TP_DEBUG ("Done waiting");
2060 InterlockedDecrement (&tp->waiting);
2061 if (mono_runtime_is_shutting_down ())
2063 must_die = should_i_die (tp);
2064 dequeue_or_steal (tp, &data);
2068 if (!data && tp->is_io && !mono_runtime_is_shutting_down ()) {
2069 mono_wsq_local_pop (&data);
2070 if (data && must_die) {
2071 InterlockedCompareExchange (&tp->destroy_thread, 1, 0);
2072 pulse_on_new_job (tp);
2081 down = mono_runtime_is_shutting_down ();
2082 if (!down && nt <= tp->min_threads)
2084 if (down || InterlockedCompareExchange (&tp->nthreads, nt - 1, nt) == nt) {
2085 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, -1);
2091 mono_profiler_thread_end (thread->tid);
2094 tp_finish_func (tp_hooks_user_data);
2101 g_assert_not_reached ();
2105 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
2107 *workerThreads = async_tp.max_threads - async_tp.busy_threads;
2108 *completionPortThreads = async_io_tp.max_threads - async_io_tp.busy_threads;
2112 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
2114 *workerThreads = async_tp.max_threads;
2115 *completionPortThreads = async_io_tp.max_threads;
2119 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
2121 *workerThreads = async_tp.min_threads;
2122 *completionPortThreads = async_io_tp.min_threads;
2126 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
2129 gint max_io_threads;
2131 max_threads = async_tp.max_threads;
2132 if (workerThreads <= 0 || workerThreads > max_threads)
2135 max_io_threads = async_io_tp.max_threads;
2136 if (completionPortThreads <= 0 || completionPortThreads > max_io_threads)
2139 InterlockedExchange (&async_tp.min_threads, workerThreads);
2140 InterlockedExchange (&async_io_tp.min_threads, completionPortThreads);
2141 if (workerThreads > async_tp.nthreads)
2142 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_tp, TRUE);
2143 if (completionPortThreads > async_io_tp.nthreads)
2144 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_io_tp, TRUE);
2149 ves_icall_System_Threading_ThreadPool_SetMaxThreads (gint workerThreads, gint completionPortThreads)
2152 gint min_io_threads;
2155 cpu_count = mono_cpu_count ();
2156 min_threads = async_tp.min_threads;
2157 if (workerThreads < min_threads || workerThreads < cpu_count)
2160 /* We don't really have the concept of completion ports. Do we care here? */
2161 min_io_threads = async_io_tp.min_threads;
2162 if (completionPortThreads < min_io_threads || completionPortThreads < cpu_count)
2165 InterlockedExchange (&async_tp.max_threads, workerThreads);
2166 InterlockedExchange (&async_io_tp.max_threads, completionPortThreads);
2171 * mono_install_threadpool_thread_hooks
2172 * @start_func: the function to be called right after a new threadpool thread is created. Can be NULL.
2173 * @finish_func: the function to be called right before a thredpool thread is exiting. Can be NULL.
2174 * @user_data: argument passed to @start_func and @finish_func.
2176 * @start_fun will be called right after a threadpool thread is created and @finish_func right before a threadpool thread exits.
2177 * The calls will be made from the thread itself.
2180 mono_install_threadpool_thread_hooks (MonoThreadPoolFunc start_func, MonoThreadPoolFunc finish_func, gpointer user_data)
2182 tp_start_func = start_func;
2183 tp_finish_func = finish_func;
2184 tp_hooks_user_data = user_data;
2188 * mono_install_threadpool_item_hooks
2189 * @begin_func: the function to be called before a threadpool work item processing starts.
2190 * @end_func: the function to be called after a threadpool work item is finished.
2191 * @user_data: argument passed to @begin_func and @end_func.
2193 * The calls will be made from the thread itself and from the same AppDomain
2194 * where the work item was executed.
2198 mono_install_threadpool_item_hooks (MonoThreadPoolItemFunc begin_func, MonoThreadPoolItemFunc end_func, gpointer user_data)
2200 tp_item_begin_func = begin_func;
2201 tp_item_end_func = end_func;
2202 tp_item_user_data = user_data;