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-2009 Novell, Inc (http://www.novell.com)
15 #define THREADS_PER_CPU 10 /* 8 + THREADS_PER_CPU * number of CPUs = max threads */
16 #define THREAD_EXIT_TIMEOUT 1000
17 #define INITIAL_QUEUE_LENGTH 128
19 #include <mono/metadata/domain-internals.h>
20 #include <mono/metadata/tabledefs.h>
21 #include <mono/metadata/threads.h>
22 #include <mono/metadata/threads-types.h>
23 #include <mono/metadata/threadpool-internals.h>
24 #include <mono/metadata/exception.h>
25 #include <mono/metadata/file-io.h>
26 #include <mono/metadata/monitor.h>
27 #include <mono/metadata/mono-mlist.h>
28 #include <mono/metadata/marshal.h>
29 #include <mono/metadata/mono-perfcounters.h>
30 #include <mono/metadata/socket-io.h>
31 #include <mono/io-layer/io-layer.h>
32 #include <mono/metadata/gc-internal.h>
33 #include <mono/utils/mono-time.h>
34 #include <mono/utils/mono-proclib.h>
36 #ifdef HAVE_SYS_TIME_H
39 #include <sys/types.h>
45 #ifdef HAVE_SYS_SOCKET_H
46 #include <sys/socket.h>
48 #include <mono/utils/mono-poll.h>
50 #include <sys/epoll.h>
53 #ifndef DISABLE_SOCKETS
54 #include "mono/io-layer/socket-wrappers.h"
57 #include "threadpool.h"
59 #define THREAD_WANTS_A_BREAK(t) ((t->state & (ThreadState_StopRequested | \
60 ThreadState_SuspendRequested)) != 0)
64 /* map of CounterSample.cs */
65 struct _MonoCounterSample {
68 gint64 counterFrequency;
69 gint64 systemFrequency;
71 gint64 timeStamp100nSec;
72 gint64 counterTimeStamp;
76 /* mono_thread_pool_init called */
79 static int pending_io_items;
82 CRITICAL_SECTION io_lock; /* access to sock_to_state */
85 MonoGHashTable *sock_to_state;
87 HANDLE new_sem; /* access to newpfd and write side of the pipe */
89 gboolean epoll_disabled;
95 static SocketIOData socket_io_data;
97 /* Keep in sync with the System.MonoAsyncCall class which provides GC tracking */
100 MonoMethodMessage *msg;
101 MonoMethod *cb_method;
102 MonoDelegate *cb_target;
106 /* This is a HANDLE, we use guint64 so the managed object layout remains constant */
111 CRITICAL_SECTION lock;
117 GQueue *idle_threads;
118 int idle_started; /* Have we started the idle threads? Interlocked */
119 /* min, max, n and busy -> Interlocked */
125 void (*async_invoke) (gpointer data);
126 void *pc_nitems; /* Performance counter for total number of items in added */
127 /* We don't need the rate here since we can compute the different ourselves */
128 /* void *perfc_rate; */
129 MonoCounterSample last_sample;
133 static ThreadPool async_tp;
134 static ThreadPool async_io_tp;
143 static void async_invoke_thread (gpointer data);
144 static void mono_async_invoke (MonoAsyncResult *ares);
145 static void threadpool_free_queue (ThreadPool *tp);
146 static void threadpool_append_job (ThreadPool *tp, MonoObject *ar);
147 static void *threadpool_queue_idle_thread (ThreadPool *tp, IdleThreadData *it);
148 static void threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer));
149 static void threadpool_start_idle_threads (ThreadPool *tp);
150 static void threadpool_kill_idle_threads (ThreadPool *tp);
152 static MonoClass *async_call_klass;
153 static MonoClass *socket_async_call_klass;
154 static MonoClass *process_async_call_klass;
156 #define INIT_POLLFD(a, b, c) {(a)->fd = b; (a)->events = c; (a)->revents = 0;}
165 AIO_OP_RECV_JUST_CALLBACK,
166 AIO_OP_SEND_JUST_CALLBACK,
171 #ifdef DISABLE_SOCKETS
172 #define socket_io_cleanup(x)
175 socket_io_cleanup (SocketIOData *data)
177 if (data->inited == 0)
180 EnterCriticalSection (&data->io_lock);
182 #ifdef PLATFORM_WIN32
183 closesocket (data->pipe [0]);
184 closesocket (data->pipe [1]);
186 close (data->pipe [0]);
187 close (data->pipe [1]);
192 CloseHandle (data->new_sem);
193 data->new_sem = NULL;
194 mono_g_hash_table_destroy (data->sock_to_state);
195 data->sock_to_state = NULL;
196 EnterCriticalSection (&async_io_tp.lock);
197 threadpool_free_queue (&async_io_tp);
198 threadpool_kill_idle_threads (&async_io_tp);
199 LeaveCriticalSection (&async_io_tp.lock);
200 g_free (data->newpfd);
203 if (FALSE == data->epoll_disabled)
204 close (data->epollfd);
206 LeaveCriticalSection (&data->io_lock);
210 get_event_from_state (MonoSocketAsyncResult *state)
212 switch (state->operation) {
215 case AIO_OP_RECV_JUST_CALLBACK:
216 case AIO_OP_RECEIVEFROM:
217 case AIO_OP_READPIPE:
220 case AIO_OP_SEND_JUST_CALLBACK:
224 default: /* Should never happen */
225 g_print ("get_event_from_state: unknown value in switch!!!\n");
231 get_events_from_list (MonoMList *list)
233 MonoSocketAsyncResult *state;
236 while (list && (state = (MonoSocketAsyncResult *)mono_mlist_get_data (list))) {
237 events |= get_event_from_state (state);
238 list = mono_mlist_next (list);
244 #define ICALL_RECV(x) ves_icall_System_Net_Sockets_Socket_Receive_internal (\
245 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
246 x->socket_flags, &x->error);
248 #define ICALL_SEND(x) ves_icall_System_Net_Sockets_Socket_Send_internal (\
249 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
250 x->socket_flags, &x->error);
252 #endif /* !DISABLE_SOCKETS */
255 threadpool_jobs_inc (MonoObject *obj)
258 InterlockedIncrement (&obj->vtable->domain->threadpool_jobs);
262 threadpool_jobs_dec (MonoObject *obj)
264 MonoDomain *domain = obj->vtable->domain;
265 int remaining_jobs = InterlockedDecrement (&domain->threadpool_jobs);
266 if (remaining_jobs == 0 && domain->cleanup_semaphore) {
267 ReleaseSemaphore (domain->cleanup_semaphore, 1, NULL);
273 #ifndef DISABLE_SOCKETS
275 async_invoke_io_thread (gpointer data)
278 MonoInternalThread *thread;
279 const gchar *version;
280 IdleThreadData idle_data = {0};
282 idle_data.timeout = INFINITE;
283 idle_data.wait_handle = CreateEvent (NULL, FALSE, FALSE, NULL);
285 thread = mono_thread_internal_current ();
287 version = mono_get_runtime_info ()->framework_version;
289 MonoSocketAsyncResult *state;
292 state = (MonoSocketAsyncResult *) data;
294 InterlockedDecrement (&pending_io_items);
296 switch (state->operation) {
298 state->total = ICALL_RECV (state);
301 state->total = ICALL_SEND (state);
305 /* worker threads invokes methods in different domains,
306 * so we need to set the right domain here */
307 domain = ((MonoObject *)ar)->vtable->domain;
311 if (domain->state == MONO_APPDOMAIN_UNLOADED || domain->state == MONO_APPDOMAIN_UNLOADING) {
312 threadpool_jobs_dec ((MonoObject *)ar);
315 mono_thread_push_appdomain_ref (domain);
316 if (threadpool_jobs_dec ((MonoObject *)ar)) {
318 mono_thread_pop_appdomain_ref ();
321 if (mono_domain_set (domain, FALSE)) {
324 mono_async_invoke (ar);
325 ac = (ASyncCall *) ar->object_data;
327 if (ac->msg->exc != NULL)
328 mono_unhandled_exception (ac->msg->exc);
330 mono_domain_set (mono_get_root_domain (), TRUE);
332 mono_thread_pop_appdomain_ref ();
333 InterlockedDecrement (&async_io_tp.busy_threads);
334 /* If the callee changes the background status, set it back to TRUE */
335 if (*version != '1' && !mono_thread_test_state (thread , ThreadState_Background))
336 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
340 data = threadpool_queue_idle_thread (&async_io_tp, &idle_data);
341 while (!idle_data.die && !data) {
343 wr = WaitForSingleObjectEx (idle_data.wait_handle, idle_data.timeout, TRUE);
344 if (THREAD_WANTS_A_BREAK (thread))
345 mono_thread_interruption_checkpoint ();
347 if (wr != WAIT_TIMEOUT && wr != WAIT_IO_COMPLETION) {
348 data = idle_data.data;
349 idle_data.data = NULL;
350 break; /* We have to exit */
355 InterlockedDecrement (&async_io_tp.nthreads);
356 CloseHandle (idle_data.wait_handle);
357 idle_data.wait_handle = NULL;
361 InterlockedIncrement (&async_io_tp.busy_threads);
364 g_assert_not_reached ();
368 process_io_event (MonoMList *list, int event)
370 MonoSocketAsyncResult *state;
376 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
377 if (get_event_from_state (state) == event)
380 list = mono_mlist_next (list);
384 oldlist = mono_mlist_remove_item (oldlist, list);
386 g_print ("Dispatching event %d on socket %p\n", event, state->handle);
388 InterlockedIncrement (&pending_io_items);
389 threadpool_append_job (&async_io_tp, (MonoObject *) state);
396 mark_bad_fds (mono_pollfd *pfds, int nfds)
402 for (i = 0; i < nfds; i++) {
407 ret = mono_poll (pfd, 1, 0);
408 if (ret == -1 && errno == EBADF) {
409 pfd->revents |= MONO_POLLNVAL;
411 } else if (ret == 1) {
420 socket_io_poll_main (gpointer p)
422 #define INITIAL_POLLFD_SIZE 1024
423 #define POLL_ERRORS (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL)
424 SocketIOData *data = p;
429 MonoInternalThread *thread;
431 thread = mono_thread_internal_current ();
433 allocated = INITIAL_POLLFD_SIZE;
434 pfds = g_new0 (mono_pollfd, allocated);
435 INIT_POLLFD (pfds, data->pipe [0], MONO_POLLIN);
436 for (i = 1; i < allocated; i++)
437 INIT_POLLFD (&pfds [i], -1, 0);
447 if (THREAD_WANTS_A_BREAK (thread))
448 mono_thread_interruption_checkpoint ();
451 nsock = mono_poll (pfds, maxfd, -1);
452 } while (nsock == -1 && errno == EINTR);
455 * Apart from EINTR, we only check EBADF, for the rest:
456 * EINVAL: mono_poll() 'protects' us from descriptor
457 * numbers above the limit if using select() by marking
458 * then as MONO_POLLERR. If a system poll() is being
459 * used, the number of descriptor we're passing will not
460 * be over sysconf(_SC_OPEN_MAX), as the error would have
461 * happened when opening.
463 * EFAULT: we own the memory pointed by pfds.
464 * ENOMEM: we're doomed anyway
468 if (nsock == -1 && errno == EBADF) {
469 pfds->revents = 0; /* Just in case... */
470 nsock = mark_bad_fds (pfds, maxfd);
473 if ((pfds->revents & POLL_ERRORS) != 0) {
474 /* We're supposed to die now, as the pipe has been closed */
476 socket_io_cleanup (data);
480 /* Got a new socket */
481 if ((pfds->revents & MONO_POLLIN) != 0) {
484 for (i = 1; i < allocated; i++) {
486 if (pfd->fd == -1 || pfd->fd == data->newpfd->fd)
490 if (i == allocated) {
495 allocated = allocated * 2;
496 pfds = g_renew (mono_pollfd, oldfd, allocated);
498 for (; i < allocated; i++)
499 INIT_POLLFD (&pfds [i], -1, 0);
501 #ifndef PLATFORM_WIN32
502 nread = read (data->pipe [0], one, 1);
504 nread = recv ((SOCKET) data->pipe [0], one, 1, 0);
508 return; /* we're closed */
511 INIT_POLLFD (&pfds [i], data->newpfd->fd, data->newpfd->events);
512 ReleaseSemaphore (data->new_sem, 1, NULL);
521 EnterCriticalSection (&data->io_lock);
522 if (data->inited == 0) {
524 LeaveCriticalSection (&data->io_lock);
525 return; /* cleanup called */
528 for (i = 1; i < maxfd && nsock > 0; i++) {
530 if (pfd->fd == -1 || pfd->revents == 0)
534 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
535 if (list != NULL && (pfd->revents & (MONO_POLLIN | POLL_ERRORS)) != 0) {
536 list = process_io_event (list, MONO_POLLIN);
539 if (list != NULL && (pfd->revents & (MONO_POLLOUT | POLL_ERRORS)) != 0) {
540 list = process_io_event (list, MONO_POLLOUT);
544 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (pfd->fd), list);
545 pfd->events = get_events_from_list (list);
547 mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
553 LeaveCriticalSection (&data->io_lock);
558 #define EPOLL_ERRORS (EPOLLERR | EPOLLHUP)
560 socket_io_epoll_main (gpointer p)
564 MonoInternalThread *thread;
565 struct epoll_event *events, *evt;
566 const int nevents = 512;
570 epollfd = data->epollfd;
571 thread = mono_thread_internal_current ();
572 events = g_new0 (struct epoll_event, nevents);
577 if (THREAD_WANTS_A_BREAK (thread))
578 mono_thread_interruption_checkpoint ();
581 g_print ("epoll_wait init\n");
583 ready = epoll_wait (epollfd, events, nevents, -1);
587 g_print ("epoll_wait end with %d ready sockets (%d %s).\n", ready, err, (err) ? g_strerror (err) : "");
591 } while (ready == -1 && errno == EINTR);
597 g_warning ("epoll_wait: %d %s\n", err, g_strerror (err));
603 EnterCriticalSection (&data->io_lock);
604 if (data->inited == 0) {
606 g_print ("data->inited == 0\n");
610 return; /* cleanup called */
613 for (i = 0; i < ready; i++) {
619 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
621 g_print ("Event %d on %d list length: %d\n", evt->events, fd, mono_mlist_length (list));
623 if (list != NULL && (evt->events & (EPOLLIN | EPOLL_ERRORS)) != 0) {
624 list = process_io_event (list, MONO_POLLIN);
627 if (list != NULL && (evt->events & (EPOLLOUT | EPOLL_ERRORS)) != 0) {
628 list = process_io_event (list, MONO_POLLOUT);
632 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (fd), list);
633 evt->events = get_events_from_list (list);
635 g_print ("MOD %d to %d\n", fd, evt->events);
637 if (epoll_ctl (epollfd, EPOLL_CTL_MOD, fd, evt)) {
638 if (epoll_ctl (epollfd, EPOLL_CTL_ADD, fd, evt) == -1) {
641 g_message ("epoll_ctl(MOD): %d %s fd: %d events: %d", err, g_strerror (err), fd, evt->events);
647 mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (fd));
649 g_print ("DEL %d\n", fd);
651 epoll_ctl (epollfd, EPOLL_CTL_DEL, fd, evt);
654 LeaveCriticalSection (&data->io_lock);
660 * select/poll wake up when a socket is closed, but epoll just removes
661 * the socket from its internal list without notification.
664 mono_thread_pool_remove_socket (int sock)
666 MonoMList *list, *next;
667 MonoSocketAsyncResult *state;
669 if (socket_io_data.inited == FALSE)
672 EnterCriticalSection (&socket_io_data.io_lock);
673 list = mono_g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
675 mono_g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
677 LeaveCriticalSection (&socket_io_data.io_lock);
680 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
681 if (state->operation == AIO_OP_RECEIVE)
682 state->operation = AIO_OP_RECV_JUST_CALLBACK;
683 else if (state->operation == AIO_OP_SEND)
684 state->operation = AIO_OP_SEND_JUST_CALLBACK;
686 next = mono_mlist_remove_item (list, list);
687 list = process_io_event (list, MONO_POLLIN);
689 process_io_event (list, MONO_POLLOUT);
695 #ifdef PLATFORM_WIN32
697 connect_hack (gpointer x)
699 struct sockaddr_in *addr = (struct sockaddr_in *) x;
702 while (connect ((SOCKET) socket_io_data.pipe [1], (SOCKADDR *) addr, sizeof (struct sockaddr_in))) {
705 g_warning ("Error initializing async. sockets %d.\n", WSAGetLastError ());
706 g_assert (WSAGetLastError ());
713 socket_io_init (SocketIOData *data)
715 #ifdef PLATFORM_WIN32
716 struct sockaddr_in server;
717 struct sockaddr_in client;
723 inited = InterlockedCompareExchange (&data->inited, -1, -1);
727 EnterCriticalSection (&data->io_lock);
728 inited = InterlockedCompareExchange (&data->inited, -1, -1);
730 LeaveCriticalSection (&data->io_lock);
735 data->epoll_disabled = (g_getenv ("MONO_DISABLE_AIO") != NULL);
736 if (FALSE == data->epoll_disabled) {
737 data->epollfd = epoll_create (256);
738 data->epoll_disabled = (data->epollfd == -1);
739 if (data->epoll_disabled && g_getenv ("MONO_DEBUG"))
740 g_message ("epoll_create() failed. Using plain poll().");
745 data->epoll_disabled = TRUE;
748 #ifndef PLATFORM_WIN32
749 if (data->epoll_disabled) {
750 if (pipe (data->pipe) != 0) {
760 srv = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
761 g_assert (srv != INVALID_SOCKET);
762 data->pipe [1] = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
763 g_assert (data->pipe [1] != INVALID_SOCKET);
765 server.sin_family = AF_INET;
766 server.sin_addr.s_addr = inet_addr ("127.0.0.1");
768 if (bind (srv, (SOCKADDR *) &server, sizeof (server))) {
769 g_print ("%d\n", WSAGetLastError ());
773 len = sizeof (server);
774 getsockname (srv, (SOCKADDR *) &server, &len);
776 mono_thread_create (mono_get_root_domain (), connect_hack, &server);
777 len = sizeof (server);
778 data->pipe [0] = accept (srv, (SOCKADDR *) &client, &len);
779 g_assert (data->pipe [0] != INVALID_SOCKET);
782 data->sock_to_state = mono_g_hash_table_new_type (g_direct_hash, g_direct_equal, MONO_HASH_VALUE_GC);
783 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_io_tp, TRUE);
785 if (data->epoll_disabled) {
786 data->new_sem = CreateSemaphore (NULL, 1, 1, NULL);
787 g_assert (data->new_sem != NULL);
789 if (data->epoll_disabled) {
790 mono_thread_create_internal (mono_get_root_domain (), socket_io_poll_main, data, TRUE);
794 mono_thread_create_internal (mono_get_root_domain (), socket_io_epoll_main, data, TRUE);
797 InterlockedCompareExchange (&data->inited, 1, 0);
798 LeaveCriticalSection (&data->io_lock);
802 socket_io_add_poll (MonoSocketAsyncResult *state)
807 SocketIOData *data = &socket_io_data;
810 #if defined(PLATFORM_MACOSX) || defined(PLATFORM_BSD) || defined(PLATFORM_WIN32) || defined(PLATFORM_SOLARIS)
811 /* select() for connect() does not work well on the Mac. Bug #75436. */
812 /* Bug #77637 for the BSD 6 case */
813 /* Bug #78888 for the Windows case */
814 if (state->operation == AIO_OP_CONNECT && state->blocking == TRUE) {
815 threadpool_append_job (&async_io_tp, (MonoObject *) state);
819 WaitForSingleObject (data->new_sem, INFINITE);
820 if (data->newpfd == NULL)
821 data->newpfd = g_new0 (mono_pollfd, 1);
823 EnterCriticalSection (&data->io_lock);
824 /* FIXME: 64 bit issue: handle can be a pointer on windows? */
825 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (state->handle));
827 list = mono_mlist_alloc ((MonoObject*)state);
829 list = mono_mlist_append (list, (MonoObject*)state);
832 events = get_events_from_list (list);
833 INIT_POLLFD (data->newpfd, GPOINTER_TO_INT (state->handle), events);
834 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (state->handle), list);
835 LeaveCriticalSection (&data->io_lock);
836 *msg = (char) state->operation;
837 #ifndef PLATFORM_WIN32
838 w = write (data->pipe [1], msg, 1);
841 send ((SOCKET) data->pipe [1], msg, 1, 0);
847 socket_io_add_epoll (MonoSocketAsyncResult *state)
850 SocketIOData *data = &socket_io_data;
851 struct epoll_event event;
855 memset (&event, 0, sizeof (struct epoll_event));
856 fd = GPOINTER_TO_INT (state->handle);
857 EnterCriticalSection (&data->io_lock);
858 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
860 list = mono_mlist_alloc ((MonoObject*)state);
861 epoll_op = EPOLL_CTL_ADD;
863 list = mono_mlist_append (list, (MonoObject*)state);
864 epoll_op = EPOLL_CTL_MOD;
867 ievt = get_events_from_list (list);
868 if ((ievt & MONO_POLLIN) != 0)
869 event.events |= EPOLLIN;
870 if ((ievt & MONO_POLLOUT) != 0)
871 event.events |= EPOLLOUT;
873 mono_g_hash_table_replace (data->sock_to_state, state->handle, list);
876 g_print ("%s %d with %d\n", epoll_op == EPOLL_CTL_ADD ? "ADD" : "MOD", fd, event.events);
878 if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
880 if (epoll_op == EPOLL_CTL_ADD && err == EEXIST) {
881 epoll_op = EPOLL_CTL_MOD;
882 if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
883 g_message ("epoll_ctl(MOD): %d %s\n", err, g_strerror (err));
888 LeaveCriticalSection (&data->io_lock);
894 socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
896 socket_io_init (&socket_io_data);
897 MONO_OBJECT_SETREF (state, ares, ares);
899 if (socket_io_data.epoll_disabled == FALSE) {
900 if (socket_io_add_epoll (state))
904 socket_io_add_poll (state);
908 socket_io_filter (MonoObject *target, MonoObject *state)
911 MonoSocketAsyncResult *sock_res = (MonoSocketAsyncResult *) state;
914 if (target == NULL || state == NULL)
917 if (socket_async_call_klass == NULL) {
918 klass = target->vtable->klass;
919 /* Check if it's SocketAsyncCall in System.Net.Sockets
920 * FIXME: check the assembly is signed correctly for extra care
922 if (klass->name [0] == 'S' && strcmp (klass->name, "SocketAsyncCall") == 0
923 && strcmp (mono_image_get_name (klass->image), "System") == 0
924 && klass->nested_in && strcmp (klass->nested_in->name, "Socket") == 0)
925 socket_async_call_klass = klass;
928 if (process_async_call_klass == NULL) {
929 klass = target->vtable->klass;
930 /* Check if it's AsyncReadHandler in System.Diagnostics.Process
931 * FIXME: check the assembly is signed correctly for extra care
933 if (klass->name [0] == 'A' && strcmp (klass->name, "AsyncReadHandler") == 0
934 && strcmp (mono_image_get_name (klass->image), "System") == 0
935 && klass->nested_in && strcmp (klass->nested_in->name, "Process") == 0)
936 process_async_call_klass = klass;
938 /* return both when socket_async_call_klass has not been seen yet and when
939 * the object is not an instance of the class.
941 if (target->vtable->klass != socket_async_call_klass && target->vtable->klass != process_async_call_klass)
944 op = sock_res->operation;
945 if (op < AIO_OP_FIRST || op >= AIO_OP_LAST)
950 #endif /* !DISABLE_SOCKETS */
953 mono_async_invoke (MonoAsyncResult *ares)
955 ASyncCall *ac = (ASyncCall *)ares->object_data;
956 MonoObject *res, *exc = NULL;
957 MonoArray *out_args = NULL;
958 HANDLE wait_event = NULL;
962 if (ares->execution_context) {
963 /* use captured ExecutionContext (if available) */
964 MONO_OBJECT_SETREF (ares, original_context, mono_thread_get_execution_context ());
965 mono_thread_set_execution_context (ares->execution_context);
967 ares->original_context = NULL;
971 res = mono_message_invoke (ares->async_delegate, ac->msg, &exc, &out_args);
972 MONO_OBJECT_SETREF (ac, res, res);
973 MONO_OBJECT_SETREF (ac, msg->exc, exc);
974 MONO_OBJECT_SETREF (ac, out_args, out_args);
976 /* call async callback if cb_method != null*/
978 MonoObject *exc = NULL;
980 mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &exc);
981 /* 'exc' will be the previous ac->msg->exc if not NULL and not
982 * catched. If catched, this will be set to NULL and the
983 * exception will not be printed. */
984 MONO_OBJECT_SETREF (ac->msg, exc, exc);
987 /* restore original thread execution context if flow isn't suppressed, i.e. non null */
988 if (ares->original_context) {
989 mono_thread_set_execution_context (ares->original_context);
990 ares->original_context = NULL;
993 /* notify listeners */
994 mono_monitor_enter ((MonoObject *) ares);
995 if (ares->handle != NULL) {
996 ac->wait_event = (gsize) mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
997 wait_event = (HANDLE)(gsize) ac->wait_event;
999 mono_monitor_exit ((MonoObject *) ares);
1000 if (wait_event != NULL)
1001 SetEvent (wait_event);
1005 threadpool_start_idle_threads (ThreadPool *tp)
1010 needed = (int) InterlockedCompareExchange (&tp->min_threads, 0, -1);
1012 existing = (int) InterlockedCompareExchange (&tp->nthreads, 0, -1);
1013 if (existing >= needed)
1015 InterlockedIncrement (&tp->nthreads);
1016 mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, NULL, TRUE);
1017 SleepEx (250, TRUE);
1022 threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer))
1024 memset (tp, 0, sizeof (ThreadPool));
1025 InitializeCriticalSection (&tp->lock);
1026 tp->min_threads = min_threads;
1027 tp->max_threads = max_threads;
1028 tp->async_invoke = async_invoke;
1029 tp->idle_threads = g_queue_new ();
1033 init_perf_counter (const char *category, const char *counter)
1035 MonoString *category_str;
1036 MonoString *counter_str;
1037 MonoString *machine;
1042 if (category == NULL || counter == NULL)
1044 root = mono_get_root_domain ();
1045 category_str = mono_string_new (root, category);
1046 counter_str = mono_string_new (root, counter);
1047 machine = mono_string_new (root, ".");
1048 return mono_perfcounter_get_impl (category_str, counter_str, NULL, machine, &type, &custom);
1052 mono_thread_pool_init ()
1054 int threads_per_cpu = THREADS_PER_CPU;
1058 if ((int) InterlockedCompareExchange (&tp_inited, 1, 0) == 1)
1061 MONO_GC_REGISTER_ROOT (socket_io_data.sock_to_state);
1062 InitializeCriticalSection (&socket_io_data.io_lock);
1063 if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
1064 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
1065 if (threads_per_cpu < THREADS_PER_CPU)
1066 threads_per_cpu = THREADS_PER_CPU;
1069 cpu_count = mono_cpu_count ();
1070 n = 8 + 2 * cpu_count; /* 8 is minFreeThreads for ASP.NET */
1071 threadpool_init (&async_tp, n, n + threads_per_cpu * cpu_count, async_invoke_thread);
1072 #ifndef DISABLE_SOCKET
1073 threadpool_init (&async_io_tp, 2 * cpu_count, 8 * cpu_count, async_invoke_io_thread);
1076 async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
1077 g_assert (async_call_klass);
1079 async_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "Work Items Added");
1080 g_assert (async_tp.pc_nitems);
1081 mono_perfcounter_get_sample (async_tp.pc_nitems, FALSE, &async_tp.last_sample);
1083 async_io_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "IO Work Items Added");
1084 g_assert (async_io_tp.pc_nitems);
1085 mono_perfcounter_get_sample (async_io_tp.pc_nitems, FALSE, &async_io_tp.last_sample);
1089 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
1092 MonoDomain *domain = mono_domain_get ();
1093 MonoAsyncResult *ares;
1096 ac = (ASyncCall*)mono_object_new (mono_domain_get (), async_call_klass);
1097 MONO_OBJECT_SETREF (ac, msg, msg);
1098 MONO_OBJECT_SETREF (ac, state, state);
1100 if (async_callback) {
1101 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
1102 MONO_OBJECT_SETREF (ac, cb_target, async_callback);
1105 ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
1106 MONO_OBJECT_SETREF (ares, async_delegate, target);
1108 #ifndef DISABLE_SOCKETS
1109 if (socket_io_filter (target, state)) {
1110 socket_io_add (ares, (MonoSocketAsyncResult *) state);
1114 if (InterlockedCompareExchange (&async_tp.idle_started, 1, 0) == 0)
1115 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_tp, TRUE);
1117 threadpool_append_job (&async_tp, (MonoObject *) ares);
1122 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1129 /* check if already finished */
1130 mono_monitor_enter ((MonoObject *) ares);
1132 if (ares->endinvoke_called) {
1133 *exc = (MonoObject *)mono_exception_from_name (mono_defaults.corlib, "System",
1134 "InvalidOperationException");
1135 mono_monitor_exit ((MonoObject *) ares);
1139 ares->endinvoke_called = 1;
1140 ac = (ASyncCall *)ares->object_data;
1142 g_assert (ac != NULL);
1144 /* wait until we are really finished */
1145 if (!ares->completed) {
1146 if (ares->handle == NULL) {
1147 ac->wait_event = (gsize)CreateEvent (NULL, TRUE, FALSE, NULL);
1148 g_assert(ac->wait_event != 0);
1149 MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), (gpointer)(gsize)ac->wait_event));
1151 mono_monitor_exit ((MonoObject *) ares);
1152 WaitForSingleObjectEx ((gpointer)(gsize)ac->wait_event, INFINITE, TRUE);
1154 mono_monitor_exit ((MonoObject *) ares);
1157 *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1158 *out_args = ac->out_args;
1164 threadpool_kill_idle_threads (ThreadPool *tp)
1168 if (!tp || !tp->idle_threads)
1171 while ((it = g_queue_pop_head (tp->idle_threads)) != NULL) {
1174 SetEvent (it->wait_handle);
1176 g_queue_free (tp->idle_threads);
1177 tp->idle_threads = NULL;
1181 mono_thread_pool_cleanup (void)
1183 EnterCriticalSection (&async_tp.lock);
1184 threadpool_free_queue (&async_tp);
1185 threadpool_kill_idle_threads (&async_tp);
1186 LeaveCriticalSection (&async_tp.lock);
1187 socket_io_cleanup (&socket_io_data); /* Empty when DISABLE_SOCKETS is defined */
1188 /* Do we want/need these?
1189 DeleteCriticalSection (&async_tp.lock);
1190 DeleteCriticalSection (&async_tp.table_lock);
1191 DeleteCriticalSection (&socket_io_data.io_lock);
1196 null_array (MonoArray *a, int first, int last)
1198 /* We must null the old array because it might
1199 contain cross-appdomain references, which
1200 will crash the GC when the domains are
1202 memset (mono_array_addr (a, MonoObject*, first), 0, sizeof (MonoObject*) * (last - first));
1205 /* Caller must enter &tp->lock */
1207 dequeue_job_nolock (ThreadPool *tp)
1212 if (!tp->array || tp->first_elem == tp->next_elem)
1214 ar = mono_array_get (tp->array, MonoObject*, tp->first_elem);
1215 mono_array_set (tp->array, MonoObject*, tp->first_elem, NULL);
1217 count = tp->next_elem - tp->first_elem;
1218 /* reduce the size of the array if it's mostly empty */
1219 if (mono_array_length (tp->array) > INITIAL_QUEUE_LENGTH && count < (mono_array_length (tp->array) / 3)) {
1220 MonoArray *newa = mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, mono_array_length (tp->array) / 2);
1221 mono_array_memcpy_refs (newa, 0, tp->array, tp->first_elem, count);
1222 null_array (tp->array, tp->first_elem, tp->next_elem);
1225 tp->next_elem = count;
1230 /* Call after entering &tp->lock */
1232 signal_idle_threads (ThreadPool *tp)
1238 njobs = tp->next_elem - tp->first_elem;
1239 while (njobs > 0 && (it = g_queue_pop_head (tp->idle_threads)) != NULL) {
1240 it->data = dequeue_job_nolock (tp);
1241 if (it->data == NULL)
1242 break; /* Should never happen */
1245 it->timeout = INFINITE;
1246 SetEvent (it->wait_handle);
1251 /* Call after entering &tp->lock */
1253 threadpool_start_thread (ThreadPool *tp, gpointer arg)
1258 max = (gint) InterlockedCompareExchange (&tp->max_threads, 0, -1);
1259 n = (gint) InterlockedCompareExchange (&tp->nthreads, 0, -1);
1262 InterlockedIncrement (&tp->nthreads);
1263 mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, arg, TRUE);
1269 get_queue_name (ThreadPool *tp)
1271 if (tp == &async_tp)
1273 if (tp == &async_io_tp)
1280 threadpool_queue_idle_thread (ThreadPool *tp, IdleThreadData *it)
1283 MonoCounterSample sample;
1286 gpointer result = NULL;
1287 CRITICAL_SECTION *cs = &tp->lock;
1289 EnterCriticalSection (cs);
1291 if (mono_100ns_ticks () - tp->last_sample.timeStamp > 10000 * 1000) {
1292 float elapsed_ticks;
1293 mono_perfcounter_get_sample (tp->pc_nitems, FALSE, &sample);
1295 elapsed_ticks = (float) (sample.timeStamp - tp->last_sample.timeStamp);
1296 rate = ((float) (sample.rawValue - tp->last_sample.rawValue)) / elapsed_ticks * 10000000;
1297 printf ("Queue: %s NThreads: %d Rate: %.2f Total items: %lld Time(ms): %.2f\n", get_queue_name (tp),
1298 InterlockedCompareExchange (&tp->nthreads, 0, -1), rate,
1299 sample.rawValue - tp->last_sample.rawValue, elapsed_ticks / 10000);
1300 memcpy (&tp->last_sample, &sample, sizeof (sample));
1304 it->data = result = dequeue_job_nolock (tp);
1305 if (result != NULL) {
1306 signal_idle_threads (tp);
1309 min = (gint) InterlockedCompareExchange (&tp->min_threads, 0, -1);
1310 n = (gint) InterlockedCompareExchange (&tp->nthreads, 0, -1);
1312 g_queue_push_tail (tp->idle_threads, it);
1314 /* TODO: figure out when threads should be told to die */
1315 /* it->die = TRUE; */
1316 g_queue_push_tail (tp->idle_threads, it);
1319 LeaveCriticalSection (cs);
1324 threadpool_append_job (ThreadPool *tp, MonoObject *ar)
1326 CRITICAL_SECTION *cs;
1329 threadpool_jobs_inc (ar);
1330 EnterCriticalSection (cs);
1331 if (ar->vtable->domain->state == MONO_APPDOMAIN_UNLOADING ||
1332 ar->vtable->domain->state == MONO_APPDOMAIN_UNLOADED) {
1333 LeaveCriticalSection (cs);
1337 mono_perfcounter_update_value (tp->pc_nitems, TRUE, 1);
1338 if (tp->array && (tp->next_elem < mono_array_length (tp->array))) {
1339 mono_array_setref (tp->array, tp->next_elem, ar);
1341 if (signal_idle_threads (tp) > 0 && threadpool_start_thread (tp, ar)) {
1343 mono_array_setref (tp->array, tp->next_elem, NULL);
1345 LeaveCriticalSection (cs);
1350 MONO_GC_REGISTER_ROOT (tp->array);
1351 tp->array = mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, INITIAL_QUEUE_LENGTH);
1353 int count = tp->next_elem - tp->first_elem;
1354 /* slide the array or create a larger one if it's full */
1355 if (tp->first_elem) {
1356 mono_array_memcpy_refs (tp->array, 0, tp->array, tp->first_elem, count);
1357 null_array (tp->array, count, tp->next_elem);
1359 MonoArray *newa = mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, mono_array_length (tp->array) * 2);
1360 mono_array_memcpy_refs (newa, 0, tp->array, tp->first_elem, count);
1361 null_array (tp->array, count, tp->next_elem);
1365 tp->next_elem = count;
1367 mono_array_setref (tp->array, tp->next_elem, ar);
1369 if (signal_idle_threads (tp) > 0 && threadpool_start_thread (tp, ar)) {
1371 mono_array_setref (tp->array, tp->next_elem, NULL);
1373 LeaveCriticalSection (cs);
1378 threadpool_clear_queue (ThreadPool *tp, MonoDomain *domain)
1381 EnterCriticalSection (&tp->lock);
1383 for (i = tp->first_elem; i < tp->next_elem; ++i) {
1384 MonoObject *obj = mono_array_get (tp->array, MonoObject*, i);
1385 if (obj->vtable->domain == domain) {
1386 mono_array_set (tp->array, MonoObject*, i, NULL);
1387 InterlockedDecrement (&domain->threadpool_jobs);
1394 for (i = tp->first_elem; i < tp->next_elem; ++i) {
1395 MonoObject *obj = mono_array_get (tp->array, MonoObject*, i);
1397 mono_array_set (tp->array, MonoObject*, idx++, obj);
1400 tp->next_elem = count;
1402 LeaveCriticalSection (&tp->lock);
1406 * Clean up the threadpool of all domain jobs.
1407 * Can only be called as part of the domain unloading process as
1408 * it will wait for all jobs to be visible to the interruption code.
1411 mono_thread_pool_remove_domain_jobs (MonoDomain *domain, int timeout)
1415 guint32 start_time = 0;
1417 g_assert (domain->state == MONO_APPDOMAIN_UNLOADING);
1419 threadpool_clear_queue (&async_tp, domain);
1420 threadpool_clear_queue (&async_io_tp, domain);
1423 * There might be some threads out that could be about to execute stuff from the given domain.
1424 * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
1426 sem_handle = CreateSemaphore (NULL, 0, 1, NULL);
1428 domain->cleanup_semaphore = sem_handle;
1430 * The memory barrier here is required to have global ordering between assigning to cleanup_semaphone
1431 * and reading threadpool_jobs.
1432 * Otherwise this thread could read a stale version of threadpool_jobs and wait forever.
1434 mono_memory_write_barrier ();
1436 if (domain->threadpool_jobs && timeout != -1)
1437 start_time = mono_msec_ticks ();
1438 while (domain->threadpool_jobs) {
1439 WaitForSingleObject (sem_handle, timeout);
1440 if (timeout != -1 && (mono_msec_ticks () - start_time) > timeout) {
1446 domain->cleanup_semaphore = NULL;
1447 CloseHandle (sem_handle);
1452 threadpool_free_queue (ThreadPool *tp)
1455 null_array (tp->array, tp->first_elem, tp->next_elem);
1457 tp->first_elem = tp->next_elem = 0;
1461 async_invoke_thread (gpointer data)
1464 MonoInternalThread *thread;
1465 const gchar *version;
1466 IdleThreadData idle_data = {0};
1468 idle_data.timeout = INFINITE;
1469 idle_data.wait_handle = CreateEvent (NULL, FALSE, FALSE, NULL);
1471 thread = mono_thread_internal_current ();
1472 version = mono_get_runtime_info ()->framework_version;
1474 MonoAsyncResult *ar;
1476 ar = (MonoAsyncResult *) data;
1478 /* worker threads invokes methods in different domains,
1479 * so we need to set the right domain here */
1480 domain = ((MonoObject *)ar)->vtable->domain;
1484 if (domain->state == MONO_APPDOMAIN_UNLOADED || domain->state == MONO_APPDOMAIN_UNLOADING) {
1485 threadpool_jobs_dec ((MonoObject *)ar);
1488 mono_thread_push_appdomain_ref (domain);
1489 if (threadpool_jobs_dec ((MonoObject *)ar)) {
1491 mono_thread_pop_appdomain_ref ();
1495 if (mono_domain_set (domain, FALSE)) {
1498 mono_async_invoke (ar);
1499 ac = (ASyncCall *) ar->object_data;
1501 if (ac->msg->exc != NULL)
1502 mono_unhandled_exception (ac->msg->exc);
1504 mono_domain_set (mono_get_root_domain (), TRUE);
1506 mono_thread_pop_appdomain_ref ();
1507 InterlockedDecrement (&async_tp.busy_threads);
1508 /* If the callee changes the background status, set it back to TRUE */
1509 if (*version != '1' && !mono_thread_test_state (thread , ThreadState_Background))
1510 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
1513 data = threadpool_queue_idle_thread (&async_tp, &idle_data);
1514 while (!idle_data.die && !data) {
1516 wr = WaitForSingleObjectEx (idle_data.wait_handle, idle_data.timeout, TRUE);
1517 if (THREAD_WANTS_A_BREAK (thread))
1518 mono_thread_interruption_checkpoint ();
1520 if (wr != WAIT_TIMEOUT && wr != WAIT_IO_COMPLETION) {
1521 data = idle_data.data;
1522 break; /* We have to exit */
1525 idle_data.data = NULL;
1528 InterlockedDecrement (&async_tp.nthreads);
1529 CloseHandle (idle_data.wait_handle);
1530 idle_data.wait_handle = NULL;
1534 InterlockedIncrement (&async_tp.busy_threads);
1537 g_assert_not_reached ();
1541 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
1545 MONO_ARCH_SAVE_REGS;
1547 busy = (gint) InterlockedCompareExchange (&async_tp.busy_threads, 0, -1);
1548 busy_io = (gint) InterlockedCompareExchange (&async_io_tp.busy_threads, 0, -1);
1549 *workerThreads = async_tp.max_threads - busy;
1550 *completionPortThreads = async_io_tp.max_threads - busy_io;
1554 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
1556 MONO_ARCH_SAVE_REGS;
1558 *workerThreads = (gint) InterlockedCompareExchange (&async_tp.max_threads, 0, -1);
1559 *completionPortThreads = (gint) InterlockedCompareExchange (&async_io_tp.max_threads, 0, -1);
1563 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
1565 gint workers, workers_io;
1567 MONO_ARCH_SAVE_REGS;
1569 workers = (gint) InterlockedCompareExchange (&async_tp.min_threads, 0, -1);
1570 workers_io = (gint) InterlockedCompareExchange (&async_io_tp.min_threads, 0, -1);
1572 *workerThreads = workers;
1573 *completionPortThreads = workers_io;
1577 start_idle_threads (void)
1579 threadpool_start_idle_threads (&async_tp);
1583 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
1585 MONO_ARCH_SAVE_REGS;
1587 if (workerThreads < 0 || workerThreads > async_tp.max_threads)
1590 if (completionPortThreads < 0 || completionPortThreads > async_io_tp.max_threads)
1593 InterlockedExchange (&async_tp.min_threads, workerThreads);
1594 InterlockedExchange (&async_io_tp.min_threads, completionPortThreads);
1595 mono_thread_create_internal (mono_get_root_domain (), start_idle_threads, NULL, TRUE);
1600 ves_icall_System_Threading_ThreadPool_SetMaxThreads (gint workerThreads, gint completionPortThreads)
1602 MONO_ARCH_SAVE_REGS;
1604 if (workerThreads < async_tp.max_threads)
1607 /* We don't really have the concept of completion ports. Do we care here? */
1608 if (completionPortThreads < async_io_tp.max_threads)
1611 InterlockedExchange (&async_tp.max_threads, workerThreads);
1612 InterlockedExchange (&async_io_tp.max_threads, completionPortThreads);