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 */
107 /* THIS FIELD IS NOT USED ANY MORE. Remove it when we feel like breaking corlib compatibility with 2.6 */
112 CRITICAL_SECTION lock;
118 GQueue *idle_threads;
119 int idle_started; /* Have we started the idle threads? Interlocked */
120 /* min, max, n and busy -> Interlocked */
126 void (*async_invoke) (gpointer data);
127 void *pc_nitems; /* Performance counter for total number of items in added */
128 /* We don't need the rate here since we can compute the different ourselves */
129 /* void *perfc_rate; */
130 MonoCounterSample last_sample;
134 static ThreadPool async_tp;
135 static ThreadPool async_io_tp;
144 static void async_invoke_thread (gpointer data);
145 static void mono_async_invoke (MonoAsyncResult *ares);
146 static void threadpool_free_queue (ThreadPool *tp);
147 static void threadpool_append_job (ThreadPool *tp, MonoObject *ar);
148 static void *threadpool_queue_idle_thread (ThreadPool *tp, IdleThreadData *it);
149 static void threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer));
150 static void threadpool_start_idle_threads (ThreadPool *tp);
151 static void threadpool_kill_idle_threads (ThreadPool *tp);
153 static MonoClass *async_call_klass;
154 static MonoClass *socket_async_call_klass;
155 static MonoClass *process_async_call_klass;
157 #define INIT_POLLFD(a, b, c) {(a)->fd = b; (a)->events = c; (a)->revents = 0;}
166 AIO_OP_RECV_JUST_CALLBACK,
167 AIO_OP_SEND_JUST_CALLBACK,
172 #ifdef DISABLE_SOCKETS
173 #define socket_io_cleanup(x)
176 socket_io_cleanup (SocketIOData *data)
178 if (data->inited == 0)
181 EnterCriticalSection (&data->io_lock);
183 #ifdef PLATFORM_WIN32
184 closesocket (data->pipe [0]);
185 closesocket (data->pipe [1]);
187 close (data->pipe [0]);
188 close (data->pipe [1]);
193 CloseHandle (data->new_sem);
194 data->new_sem = NULL;
195 mono_g_hash_table_destroy (data->sock_to_state);
196 data->sock_to_state = NULL;
197 EnterCriticalSection (&async_io_tp.lock);
198 threadpool_free_queue (&async_io_tp);
199 threadpool_kill_idle_threads (&async_io_tp);
200 LeaveCriticalSection (&async_io_tp.lock);
201 g_free (data->newpfd);
204 if (FALSE == data->epoll_disabled)
205 close (data->epollfd);
207 LeaveCriticalSection (&data->io_lock);
211 get_event_from_state (MonoSocketAsyncResult *state)
213 switch (state->operation) {
216 case AIO_OP_RECV_JUST_CALLBACK:
217 case AIO_OP_RECEIVEFROM:
218 case AIO_OP_READPIPE:
221 case AIO_OP_SEND_JUST_CALLBACK:
225 default: /* Should never happen */
226 g_print ("get_event_from_state: unknown value in switch!!!\n");
232 get_events_from_list (MonoMList *list)
234 MonoSocketAsyncResult *state;
237 while (list && (state = (MonoSocketAsyncResult *)mono_mlist_get_data (list))) {
238 events |= get_event_from_state (state);
239 list = mono_mlist_next (list);
245 #define ICALL_RECV(x) ves_icall_System_Net_Sockets_Socket_Receive_internal (\
246 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
247 x->socket_flags, &x->error);
249 #define ICALL_SEND(x) ves_icall_System_Net_Sockets_Socket_Send_internal (\
250 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
251 x->socket_flags, &x->error);
253 #endif /* !DISABLE_SOCKETS */
256 threadpool_jobs_inc (MonoObject *obj)
259 InterlockedIncrement (&obj->vtable->domain->threadpool_jobs);
263 threadpool_jobs_dec (MonoObject *obj)
265 MonoDomain *domain = obj->vtable->domain;
266 int remaining_jobs = InterlockedDecrement (&domain->threadpool_jobs);
267 if (remaining_jobs == 0 && domain->cleanup_semaphore) {
268 ReleaseSemaphore (domain->cleanup_semaphore, 1, NULL);
274 #ifndef DISABLE_SOCKETS
276 async_invoke_io_thread (gpointer data)
279 MonoInternalThread *thread;
280 const gchar *version;
281 IdleThreadData idle_data = {0};
283 idle_data.timeout = INFINITE;
284 idle_data.wait_handle = CreateEvent (NULL, FALSE, FALSE, NULL);
286 thread = mono_thread_internal_current ();
288 version = mono_get_runtime_info ()->framework_version;
290 MonoSocketAsyncResult *state;
293 state = (MonoSocketAsyncResult *) data;
295 InterlockedDecrement (&pending_io_items);
297 switch (state->operation) {
299 state->total = ICALL_RECV (state);
302 state->total = ICALL_SEND (state);
306 /* worker threads invokes methods in different domains,
307 * so we need to set the right domain here */
308 domain = ((MonoObject *)ar)->vtable->domain;
312 if (domain->state == MONO_APPDOMAIN_UNLOADED || domain->state == MONO_APPDOMAIN_UNLOADING) {
313 threadpool_jobs_dec ((MonoObject *)ar);
316 mono_thread_push_appdomain_ref (domain);
317 if (threadpool_jobs_dec ((MonoObject *)ar)) {
319 mono_thread_pop_appdomain_ref ();
322 if (mono_domain_set (domain, FALSE)) {
325 mono_async_invoke (ar);
326 ac = (ASyncCall *) ar->object_data;
328 if (ac->msg->exc != NULL)
329 mono_unhandled_exception (ac->msg->exc);
331 mono_domain_set (mono_get_root_domain (), TRUE);
333 mono_thread_pop_appdomain_ref ();
334 InterlockedDecrement (&async_io_tp.busy_threads);
335 /* If the callee changes the background status, set it back to TRUE */
336 if (*version != '1' && !mono_thread_test_state (thread , ThreadState_Background))
337 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
341 data = threadpool_queue_idle_thread (&async_io_tp, &idle_data);
342 while (!idle_data.die && !data) {
344 wr = WaitForSingleObjectEx (idle_data.wait_handle, idle_data.timeout, TRUE);
345 if (THREAD_WANTS_A_BREAK (thread))
346 mono_thread_interruption_checkpoint ();
348 if (wr != WAIT_TIMEOUT && wr != WAIT_IO_COMPLETION) {
349 data = idle_data.data;
350 idle_data.data = NULL;
351 break; /* We have to exit */
356 InterlockedDecrement (&async_io_tp.nthreads);
357 CloseHandle (idle_data.wait_handle);
358 idle_data.wait_handle = NULL;
362 InterlockedIncrement (&async_io_tp.busy_threads);
365 g_assert_not_reached ();
369 process_io_event (MonoMList *list, int event)
371 MonoSocketAsyncResult *state;
377 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
378 if (get_event_from_state (state) == event)
381 list = mono_mlist_next (list);
385 oldlist = mono_mlist_remove_item (oldlist, list);
387 g_print ("Dispatching event %d on socket %p\n", event, state->handle);
389 InterlockedIncrement (&pending_io_items);
390 threadpool_append_job (&async_io_tp, (MonoObject *) state);
397 mark_bad_fds (mono_pollfd *pfds, int nfds)
403 for (i = 0; i < nfds; i++) {
408 ret = mono_poll (pfd, 1, 0);
409 if (ret == -1 && errno == EBADF) {
410 pfd->revents |= MONO_POLLNVAL;
412 } else if (ret == 1) {
421 socket_io_poll_main (gpointer p)
423 #define INITIAL_POLLFD_SIZE 1024
424 #define POLL_ERRORS (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL)
425 SocketIOData *data = p;
430 MonoInternalThread *thread;
432 thread = mono_thread_internal_current ();
434 allocated = INITIAL_POLLFD_SIZE;
435 pfds = g_new0 (mono_pollfd, allocated);
436 INIT_POLLFD (pfds, data->pipe [0], MONO_POLLIN);
437 for (i = 1; i < allocated; i++)
438 INIT_POLLFD (&pfds [i], -1, 0);
448 if (THREAD_WANTS_A_BREAK (thread))
449 mono_thread_interruption_checkpoint ();
452 nsock = mono_poll (pfds, maxfd, -1);
453 } while (nsock == -1 && errno == EINTR);
456 * Apart from EINTR, we only check EBADF, for the rest:
457 * EINVAL: mono_poll() 'protects' us from descriptor
458 * numbers above the limit if using select() by marking
459 * then as MONO_POLLERR. If a system poll() is being
460 * used, the number of descriptor we're passing will not
461 * be over sysconf(_SC_OPEN_MAX), as the error would have
462 * happened when opening.
464 * EFAULT: we own the memory pointed by pfds.
465 * ENOMEM: we're doomed anyway
469 if (nsock == -1 && errno == EBADF) {
470 pfds->revents = 0; /* Just in case... */
471 nsock = mark_bad_fds (pfds, maxfd);
474 if ((pfds->revents & POLL_ERRORS) != 0) {
475 /* We're supposed to die now, as the pipe has been closed */
477 socket_io_cleanup (data);
481 /* Got a new socket */
482 if ((pfds->revents & MONO_POLLIN) != 0) {
485 for (i = 1; i < allocated; i++) {
487 if (pfd->fd == -1 || pfd->fd == data->newpfd->fd)
491 if (i == allocated) {
496 allocated = allocated * 2;
497 pfds = g_renew (mono_pollfd, oldfd, allocated);
499 for (; i < allocated; i++)
500 INIT_POLLFD (&pfds [i], -1, 0);
502 #ifndef PLATFORM_WIN32
503 nread = read (data->pipe [0], one, 1);
505 nread = recv ((SOCKET) data->pipe [0], one, 1, 0);
509 return; /* we're closed */
512 INIT_POLLFD (&pfds [i], data->newpfd->fd, data->newpfd->events);
513 ReleaseSemaphore (data->new_sem, 1, NULL);
522 EnterCriticalSection (&data->io_lock);
523 if (data->inited == 0) {
525 LeaveCriticalSection (&data->io_lock);
526 return; /* cleanup called */
529 for (i = 1; i < maxfd && nsock > 0; i++) {
531 if (pfd->fd == -1 || pfd->revents == 0)
535 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
536 if (list != NULL && (pfd->revents & (MONO_POLLIN | POLL_ERRORS)) != 0) {
537 list = process_io_event (list, MONO_POLLIN);
540 if (list != NULL && (pfd->revents & (MONO_POLLOUT | POLL_ERRORS)) != 0) {
541 list = process_io_event (list, MONO_POLLOUT);
545 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (pfd->fd), list);
546 pfd->events = get_events_from_list (list);
548 mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
554 LeaveCriticalSection (&data->io_lock);
559 #define EPOLL_ERRORS (EPOLLERR | EPOLLHUP)
561 socket_io_epoll_main (gpointer p)
565 MonoInternalThread *thread;
566 struct epoll_event *events, *evt;
567 const int nevents = 512;
571 epollfd = data->epollfd;
572 thread = mono_thread_internal_current ();
573 events = g_new0 (struct epoll_event, nevents);
578 if (THREAD_WANTS_A_BREAK (thread))
579 mono_thread_interruption_checkpoint ();
582 g_print ("epoll_wait init\n");
584 ready = epoll_wait (epollfd, events, nevents, -1);
588 g_print ("epoll_wait end with %d ready sockets (%d %s).\n", ready, err, (err) ? g_strerror (err) : "");
592 } while (ready == -1 && errno == EINTR);
598 g_warning ("epoll_wait: %d %s\n", err, g_strerror (err));
604 EnterCriticalSection (&data->io_lock);
605 if (data->inited == 0) {
607 g_print ("data->inited == 0\n");
611 return; /* cleanup called */
614 for (i = 0; i < ready; i++) {
620 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
622 g_print ("Event %d on %d list length: %d\n", evt->events, fd, mono_mlist_length (list));
624 if (list != NULL && (evt->events & (EPOLLIN | EPOLL_ERRORS)) != 0) {
625 list = process_io_event (list, MONO_POLLIN);
628 if (list != NULL && (evt->events & (EPOLLOUT | EPOLL_ERRORS)) != 0) {
629 list = process_io_event (list, MONO_POLLOUT);
633 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (fd), list);
634 evt->events = get_events_from_list (list);
636 g_print ("MOD %d to %d\n", fd, evt->events);
638 if (epoll_ctl (epollfd, EPOLL_CTL_MOD, fd, evt)) {
639 if (epoll_ctl (epollfd, EPOLL_CTL_ADD, fd, evt) == -1) {
642 g_message ("epoll_ctl(MOD): %d %s fd: %d events: %d", err, g_strerror (err), fd, evt->events);
648 mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (fd));
650 g_print ("DEL %d\n", fd);
652 epoll_ctl (epollfd, EPOLL_CTL_DEL, fd, evt);
655 LeaveCriticalSection (&data->io_lock);
661 * select/poll wake up when a socket is closed, but epoll just removes
662 * the socket from its internal list without notification.
665 mono_thread_pool_remove_socket (int sock)
667 MonoMList *list, *next;
668 MonoSocketAsyncResult *state;
670 if (socket_io_data.inited == FALSE)
673 EnterCriticalSection (&socket_io_data.io_lock);
674 list = mono_g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
676 mono_g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
678 LeaveCriticalSection (&socket_io_data.io_lock);
681 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
682 if (state->operation == AIO_OP_RECEIVE)
683 state->operation = AIO_OP_RECV_JUST_CALLBACK;
684 else if (state->operation == AIO_OP_SEND)
685 state->operation = AIO_OP_SEND_JUST_CALLBACK;
687 next = mono_mlist_remove_item (list, list);
688 list = process_io_event (list, MONO_POLLIN);
690 process_io_event (list, MONO_POLLOUT);
696 #ifdef PLATFORM_WIN32
698 connect_hack (gpointer x)
700 struct sockaddr_in *addr = (struct sockaddr_in *) x;
703 while (connect ((SOCKET) socket_io_data.pipe [1], (SOCKADDR *) addr, sizeof (struct sockaddr_in))) {
706 g_warning ("Error initializing async. sockets %d.\n", WSAGetLastError ());
707 g_assert (WSAGetLastError ());
714 socket_io_init (SocketIOData *data)
716 #ifdef PLATFORM_WIN32
717 struct sockaddr_in server;
718 struct sockaddr_in client;
724 inited = InterlockedCompareExchange (&data->inited, -1, -1);
728 EnterCriticalSection (&data->io_lock);
729 inited = InterlockedCompareExchange (&data->inited, -1, -1);
731 LeaveCriticalSection (&data->io_lock);
736 data->epoll_disabled = (g_getenv ("MONO_DISABLE_AIO") != NULL);
737 if (FALSE == data->epoll_disabled) {
738 data->epollfd = epoll_create (256);
739 data->epoll_disabled = (data->epollfd == -1);
740 if (data->epoll_disabled && g_getenv ("MONO_DEBUG"))
741 g_message ("epoll_create() failed. Using plain poll().");
746 data->epoll_disabled = TRUE;
749 #ifndef PLATFORM_WIN32
750 if (data->epoll_disabled) {
751 if (pipe (data->pipe) != 0) {
761 srv = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
762 g_assert (srv != INVALID_SOCKET);
763 data->pipe [1] = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
764 g_assert (data->pipe [1] != INVALID_SOCKET);
766 server.sin_family = AF_INET;
767 server.sin_addr.s_addr = inet_addr ("127.0.0.1");
769 if (bind (srv, (SOCKADDR *) &server, sizeof (server))) {
770 g_print ("%d\n", WSAGetLastError ());
774 len = sizeof (server);
775 getsockname (srv, (SOCKADDR *) &server, &len);
777 mono_thread_create (mono_get_root_domain (), connect_hack, &server);
778 len = sizeof (server);
779 data->pipe [0] = accept (srv, (SOCKADDR *) &client, &len);
780 g_assert (data->pipe [0] != INVALID_SOCKET);
783 data->sock_to_state = mono_g_hash_table_new_type (g_direct_hash, g_direct_equal, MONO_HASH_VALUE_GC);
784 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_io_tp, TRUE);
786 if (data->epoll_disabled) {
787 data->new_sem = CreateSemaphore (NULL, 1, 1, NULL);
788 g_assert (data->new_sem != NULL);
790 if (data->epoll_disabled) {
791 mono_thread_create_internal (mono_get_root_domain (), socket_io_poll_main, data, TRUE);
795 mono_thread_create_internal (mono_get_root_domain (), socket_io_epoll_main, data, TRUE);
798 InterlockedCompareExchange (&data->inited, 1, 0);
799 LeaveCriticalSection (&data->io_lock);
803 socket_io_add_poll (MonoSocketAsyncResult *state)
808 SocketIOData *data = &socket_io_data;
811 #if defined(PLATFORM_MACOSX) || defined(PLATFORM_BSD) || defined(PLATFORM_WIN32) || defined(PLATFORM_SOLARIS)
812 /* select() for connect() does not work well on the Mac. Bug #75436. */
813 /* Bug #77637 for the BSD 6 case */
814 /* Bug #78888 for the Windows case */
815 if (state->operation == AIO_OP_CONNECT && state->blocking == TRUE) {
816 threadpool_append_job (&async_io_tp, (MonoObject *) state);
820 WaitForSingleObject (data->new_sem, INFINITE);
821 if (data->newpfd == NULL)
822 data->newpfd = g_new0 (mono_pollfd, 1);
824 EnterCriticalSection (&data->io_lock);
825 /* FIXME: 64 bit issue: handle can be a pointer on windows? */
826 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (state->handle));
828 list = mono_mlist_alloc ((MonoObject*)state);
830 list = mono_mlist_append (list, (MonoObject*)state);
833 events = get_events_from_list (list);
834 INIT_POLLFD (data->newpfd, GPOINTER_TO_INT (state->handle), events);
835 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (state->handle), list);
836 LeaveCriticalSection (&data->io_lock);
837 *msg = (char) state->operation;
838 #ifndef PLATFORM_WIN32
839 w = write (data->pipe [1], msg, 1);
842 send ((SOCKET) data->pipe [1], msg, 1, 0);
848 socket_io_add_epoll (MonoSocketAsyncResult *state)
851 SocketIOData *data = &socket_io_data;
852 struct epoll_event event;
856 memset (&event, 0, sizeof (struct epoll_event));
857 fd = GPOINTER_TO_INT (state->handle);
858 EnterCriticalSection (&data->io_lock);
859 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
861 list = mono_mlist_alloc ((MonoObject*)state);
862 epoll_op = EPOLL_CTL_ADD;
864 list = mono_mlist_append (list, (MonoObject*)state);
865 epoll_op = EPOLL_CTL_MOD;
868 ievt = get_events_from_list (list);
869 if ((ievt & MONO_POLLIN) != 0)
870 event.events |= EPOLLIN;
871 if ((ievt & MONO_POLLOUT) != 0)
872 event.events |= EPOLLOUT;
874 mono_g_hash_table_replace (data->sock_to_state, state->handle, list);
877 g_print ("%s %d with %d\n", epoll_op == EPOLL_CTL_ADD ? "ADD" : "MOD", fd, event.events);
879 if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
881 if (epoll_op == EPOLL_CTL_ADD && err == EEXIST) {
882 epoll_op = EPOLL_CTL_MOD;
883 if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
884 g_message ("epoll_ctl(MOD): %d %s\n", err, g_strerror (err));
889 LeaveCriticalSection (&data->io_lock);
895 socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
897 socket_io_init (&socket_io_data);
898 MONO_OBJECT_SETREF (state, ares, ares);
900 if (socket_io_data.epoll_disabled == FALSE) {
901 if (socket_io_add_epoll (state))
905 socket_io_add_poll (state);
909 socket_io_filter (MonoObject *target, MonoObject *state)
912 MonoSocketAsyncResult *sock_res = (MonoSocketAsyncResult *) state;
915 if (target == NULL || state == NULL)
918 if (socket_async_call_klass == NULL) {
919 klass = target->vtable->klass;
920 /* Check if it's SocketAsyncCall in System.Net.Sockets
921 * FIXME: check the assembly is signed correctly for extra care
923 if (klass->name [0] == 'S' && strcmp (klass->name, "SocketAsyncCall") == 0
924 && strcmp (mono_image_get_name (klass->image), "System") == 0
925 && klass->nested_in && strcmp (klass->nested_in->name, "Socket") == 0)
926 socket_async_call_klass = klass;
929 if (process_async_call_klass == NULL) {
930 klass = target->vtable->klass;
931 /* Check if it's AsyncReadHandler in System.Diagnostics.Process
932 * FIXME: check the assembly is signed correctly for extra care
934 if (klass->name [0] == 'A' && strcmp (klass->name, "AsyncReadHandler") == 0
935 && strcmp (mono_image_get_name (klass->image), "System") == 0
936 && klass->nested_in && strcmp (klass->nested_in->name, "Process") == 0)
937 process_async_call_klass = klass;
939 /* return both when socket_async_call_klass has not been seen yet and when
940 * the object is not an instance of the class.
942 if (target->vtable->klass != socket_async_call_klass && target->vtable->klass != process_async_call_klass)
945 op = sock_res->operation;
946 if (op < AIO_OP_FIRST || op >= AIO_OP_LAST)
951 #endif /* !DISABLE_SOCKETS */
954 mono_async_invoke (MonoAsyncResult *ares)
956 ASyncCall *ac = (ASyncCall *)ares->object_data;
957 MonoObject *res, *exc = NULL;
958 MonoArray *out_args = NULL;
959 HANDLE wait_event = NULL;
961 if (ares->execution_context) {
962 /* use captured ExecutionContext (if available) */
963 MONO_OBJECT_SETREF (ares, original_context, mono_thread_get_execution_context ());
964 mono_thread_set_execution_context (ares->execution_context);
966 ares->original_context = NULL;
970 res = mono_message_invoke (ares->async_delegate, ac->msg, &exc, &out_args);
971 MONO_OBJECT_SETREF (ac, res, res);
972 MONO_OBJECT_SETREF (ac, msg->exc, exc);
973 MONO_OBJECT_SETREF (ac, out_args, out_args);
975 mono_monitor_enter ((MonoObject *) ares);
977 if (ares->handle != NULL)
978 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
979 mono_monitor_exit ((MonoObject *) ares);
980 /* notify listeners */
981 if (wait_event != NULL)
982 SetEvent (wait_event);
984 /* call async callback if cb_method != null*/
986 MonoObject *exc = NULL;
988 mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &exc);
989 /* 'exc' will be the previous ac->msg->exc if not NULL and not
990 * catched. If catched, this will be set to NULL and the
991 * exception will not be printed. */
992 MONO_OBJECT_SETREF (ac->msg, exc, exc);
995 /* restore original thread execution context if flow isn't suppressed, i.e. non null */
996 if (ares->original_context) {
997 mono_thread_set_execution_context (ares->original_context);
998 ares->original_context = NULL;
1004 threadpool_start_idle_threads (ThreadPool *tp)
1009 needed = (int) InterlockedCompareExchange (&tp->min_threads, 0, -1);
1011 existing = (int) InterlockedCompareExchange (&tp->nthreads, 0, -1);
1012 if (existing >= needed)
1014 InterlockedIncrement (&tp->nthreads);
1015 mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, NULL, TRUE);
1016 SleepEx (250, TRUE);
1021 threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer))
1023 memset (tp, 0, sizeof (ThreadPool));
1024 InitializeCriticalSection (&tp->lock);
1025 tp->min_threads = min_threads;
1026 tp->max_threads = max_threads;
1027 tp->async_invoke = async_invoke;
1028 tp->idle_threads = g_queue_new ();
1032 init_perf_counter (const char *category, const char *counter)
1034 MonoString *category_str;
1035 MonoString *counter_str;
1036 MonoString *machine;
1041 if (category == NULL || counter == NULL)
1043 root = mono_get_root_domain ();
1044 category_str = mono_string_new (root, category);
1045 counter_str = mono_string_new (root, counter);
1046 machine = mono_string_new (root, ".");
1047 return mono_perfcounter_get_impl (category_str, counter_str, NULL, machine, &type, &custom);
1051 mono_thread_pool_init ()
1053 int threads_per_cpu = THREADS_PER_CPU;
1057 if ((int) InterlockedCompareExchange (&tp_inited, 1, 0) == 1)
1060 MONO_GC_REGISTER_ROOT (socket_io_data.sock_to_state);
1061 InitializeCriticalSection (&socket_io_data.io_lock);
1062 if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
1063 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
1064 if (threads_per_cpu < THREADS_PER_CPU)
1065 threads_per_cpu = THREADS_PER_CPU;
1068 cpu_count = mono_cpu_count ();
1069 n = 8 + 2 * cpu_count; /* 8 is minFreeThreads for ASP.NET */
1070 threadpool_init (&async_tp, n, n + threads_per_cpu * cpu_count, async_invoke_thread);
1071 #ifndef DISABLE_SOCKET
1072 threadpool_init (&async_io_tp, 2 * cpu_count, 8 * cpu_count, async_invoke_io_thread);
1075 async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
1076 g_assert (async_call_klass);
1078 async_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "Work Items Added");
1079 g_assert (async_tp.pc_nitems);
1080 mono_perfcounter_get_sample (async_tp.pc_nitems, FALSE, &async_tp.last_sample);
1082 async_io_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "IO Work Items Added");
1083 g_assert (async_io_tp.pc_nitems);
1084 mono_perfcounter_get_sample (async_io_tp.pc_nitems, FALSE, &async_io_tp.last_sample);
1088 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
1091 MonoDomain *domain = mono_domain_get ();
1092 MonoAsyncResult *ares;
1095 ac = (ASyncCall*)mono_object_new (mono_domain_get (), async_call_klass);
1096 MONO_OBJECT_SETREF (ac, msg, msg);
1097 MONO_OBJECT_SETREF (ac, state, state);
1099 if (async_callback) {
1100 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
1101 MONO_OBJECT_SETREF (ac, cb_target, async_callback);
1104 ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
1105 MONO_OBJECT_SETREF (ares, async_delegate, target);
1107 #ifndef DISABLE_SOCKETS
1108 if (socket_io_filter (target, state)) {
1109 socket_io_add (ares, (MonoSocketAsyncResult *) state);
1113 if (InterlockedCompareExchange (&async_tp.idle_started, 1, 0) == 0)
1114 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_tp, TRUE);
1116 threadpool_append_job (&async_tp, (MonoObject *) ares);
1121 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 /* wait until we are really finished */
1141 if (!ares->completed) {
1142 if (ares->handle == NULL) {
1143 wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1144 g_assert(wait_event != 0);
1145 MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), wait_event));
1147 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
1149 mono_monitor_exit ((MonoObject *) ares);
1150 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
1152 mono_monitor_exit ((MonoObject *) ares);
1155 ac = (ASyncCall *) ares->object_data;
1156 g_assert (ac != NULL);
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);
1290 if (tp->idle_threads == NULL) {
1292 return NULL; /* We are shutting down */
1295 if (mono_100ns_ticks () - tp->last_sample.timeStamp > 10000 * 1000) {
1296 float elapsed_ticks;
1297 mono_perfcounter_get_sample (tp->pc_nitems, FALSE, &sample);
1299 elapsed_ticks = (float) (sample.timeStamp - tp->last_sample.timeStamp);
1300 rate = ((float) (sample.rawValue - tp->last_sample.rawValue)) / elapsed_ticks * 10000000;
1301 printf ("Queue: %s NThreads: %d Rate: %.2f Total items: %lld Time(ms): %.2f\n", get_queue_name (tp),
1302 InterlockedCompareExchange (&tp->nthreads, 0, -1), rate,
1303 sample.rawValue - tp->last_sample.rawValue, elapsed_ticks / 10000);
1304 memcpy (&tp->last_sample, &sample, sizeof (sample));
1308 it->data = result = dequeue_job_nolock (tp);
1309 if (result != NULL) {
1310 signal_idle_threads (tp);
1313 min = (gint) InterlockedCompareExchange (&tp->min_threads, 0, -1);
1314 n = (gint) InterlockedCompareExchange (&tp->nthreads, 0, -1);
1316 g_queue_push_tail (tp->idle_threads, it);
1318 /* TODO: figure out when threads should be told to die */
1319 /* it->die = TRUE; */
1320 g_queue_push_tail (tp->idle_threads, it);
1323 LeaveCriticalSection (cs);
1328 threadpool_append_job (ThreadPool *tp, MonoObject *ar)
1330 CRITICAL_SECTION *cs;
1333 threadpool_jobs_inc (ar);
1334 EnterCriticalSection (cs);
1335 if (tp->idle_threads == NULL)
1336 return; /* We are shutting down */
1337 if (ar->vtable->domain->state == MONO_APPDOMAIN_UNLOADING ||
1338 ar->vtable->domain->state == MONO_APPDOMAIN_UNLOADED) {
1339 LeaveCriticalSection (cs);
1343 mono_perfcounter_update_value (tp->pc_nitems, TRUE, 1);
1344 if (tp->array && (tp->next_elem < mono_array_length (tp->array))) {
1345 mono_array_setref (tp->array, tp->next_elem, ar);
1347 if (signal_idle_threads (tp) > 0 && threadpool_start_thread (tp, ar)) {
1349 mono_array_setref (tp->array, tp->next_elem, NULL);
1351 LeaveCriticalSection (cs);
1356 MONO_GC_REGISTER_ROOT (tp->array);
1357 tp->array = mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, INITIAL_QUEUE_LENGTH);
1359 int count = tp->next_elem - tp->first_elem;
1360 /* slide the array or create a larger one if it's full */
1361 if (tp->first_elem) {
1362 mono_array_memcpy_refs (tp->array, 0, tp->array, tp->first_elem, count);
1363 null_array (tp->array, count, tp->next_elem);
1365 MonoArray *newa = mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, mono_array_length (tp->array) * 2);
1366 mono_array_memcpy_refs (newa, 0, tp->array, tp->first_elem, count);
1367 null_array (tp->array, count, tp->next_elem);
1371 tp->next_elem = count;
1373 mono_array_setref (tp->array, tp->next_elem, ar);
1375 if (signal_idle_threads (tp) > 0 && threadpool_start_thread (tp, ar)) {
1377 mono_array_setref (tp->array, tp->next_elem, NULL);
1379 LeaveCriticalSection (cs);
1384 threadpool_clear_queue (ThreadPool *tp, MonoDomain *domain)
1387 EnterCriticalSection (&tp->lock);
1389 for (i = tp->first_elem; i < tp->next_elem; ++i) {
1390 MonoObject *obj = mono_array_get (tp->array, MonoObject*, i);
1391 if (obj->vtable->domain == domain) {
1392 mono_array_set (tp->array, MonoObject*, i, NULL);
1393 InterlockedDecrement (&domain->threadpool_jobs);
1400 for (i = tp->first_elem; i < tp->next_elem; ++i) {
1401 MonoObject *obj = mono_array_get (tp->array, MonoObject*, i);
1403 mono_array_set (tp->array, MonoObject*, idx++, obj);
1406 tp->next_elem = count;
1408 LeaveCriticalSection (&tp->lock);
1412 * Clean up the threadpool of all domain jobs.
1413 * Can only be called as part of the domain unloading process as
1414 * it will wait for all jobs to be visible to the interruption code.
1417 mono_thread_pool_remove_domain_jobs (MonoDomain *domain, int timeout)
1421 guint32 start_time = 0;
1423 g_assert (domain->state == MONO_APPDOMAIN_UNLOADING);
1425 threadpool_clear_queue (&async_tp, domain);
1426 threadpool_clear_queue (&async_io_tp, domain);
1429 * There might be some threads out that could be about to execute stuff from the given domain.
1430 * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
1432 sem_handle = CreateSemaphore (NULL, 0, 1, NULL);
1434 domain->cleanup_semaphore = sem_handle;
1436 * The memory barrier here is required to have global ordering between assigning to cleanup_semaphone
1437 * and reading threadpool_jobs.
1438 * Otherwise this thread could read a stale version of threadpool_jobs and wait forever.
1440 mono_memory_write_barrier ();
1442 if (domain->threadpool_jobs && timeout != -1)
1443 start_time = mono_msec_ticks ();
1444 while (domain->threadpool_jobs) {
1445 WaitForSingleObject (sem_handle, timeout);
1446 if (timeout != -1 && (mono_msec_ticks () - start_time) > timeout) {
1452 domain->cleanup_semaphore = NULL;
1453 CloseHandle (sem_handle);
1458 threadpool_free_queue (ThreadPool *tp)
1461 null_array (tp->array, tp->first_elem, tp->next_elem);
1463 tp->first_elem = tp->next_elem = 0;
1467 mono_thread_pool_is_queue_array (MonoArray *o)
1469 return o == async_tp.array || o == async_io_tp.array;
1473 async_invoke_thread (gpointer data)
1476 MonoInternalThread *thread;
1477 const gchar *version;
1478 IdleThreadData idle_data = {0};
1480 idle_data.timeout = INFINITE;
1481 idle_data.wait_handle = CreateEvent (NULL, FALSE, FALSE, NULL);
1483 thread = mono_thread_internal_current ();
1484 version = mono_get_runtime_info ()->framework_version;
1486 MonoAsyncResult *ar;
1488 ar = (MonoAsyncResult *) data;
1490 /* worker threads invokes methods in different domains,
1491 * so we need to set the right domain here */
1492 domain = ((MonoObject *)ar)->vtable->domain;
1496 if (domain->state == MONO_APPDOMAIN_UNLOADED || domain->state == MONO_APPDOMAIN_UNLOADING) {
1497 threadpool_jobs_dec ((MonoObject *)ar);
1500 mono_thread_push_appdomain_ref (domain);
1501 if (threadpool_jobs_dec ((MonoObject *)ar)) {
1503 mono_thread_pop_appdomain_ref ();
1507 if (mono_domain_set (domain, FALSE)) {
1510 mono_async_invoke (ar);
1511 ac = (ASyncCall *) ar->object_data;
1513 if (ac->msg->exc != NULL)
1514 mono_unhandled_exception (ac->msg->exc);
1516 mono_domain_set (mono_get_root_domain (), TRUE);
1518 mono_thread_pop_appdomain_ref ();
1519 InterlockedDecrement (&async_tp.busy_threads);
1520 /* If the callee changes the background status, set it back to TRUE */
1521 if (*version != '1' && !mono_thread_test_state (thread , ThreadState_Background))
1522 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
1525 data = threadpool_queue_idle_thread (&async_tp, &idle_data);
1526 while (!idle_data.die && !data) {
1528 wr = WaitForSingleObjectEx (idle_data.wait_handle, idle_data.timeout, TRUE);
1529 if (THREAD_WANTS_A_BREAK (thread))
1530 mono_thread_interruption_checkpoint ();
1532 if (wr != WAIT_TIMEOUT && wr != WAIT_IO_COMPLETION) {
1533 data = idle_data.data;
1534 break; /* We have to exit */
1537 idle_data.data = NULL;
1540 InterlockedDecrement (&async_tp.nthreads);
1541 CloseHandle (idle_data.wait_handle);
1542 idle_data.wait_handle = NULL;
1546 InterlockedIncrement (&async_tp.busy_threads);
1549 g_assert_not_reached ();
1553 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
1557 MONO_ARCH_SAVE_REGS;
1559 busy = (gint) InterlockedCompareExchange (&async_tp.busy_threads, 0, -1);
1560 busy_io = (gint) InterlockedCompareExchange (&async_io_tp.busy_threads, 0, -1);
1561 *workerThreads = async_tp.max_threads - busy;
1562 *completionPortThreads = async_io_tp.max_threads - busy_io;
1566 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
1568 MONO_ARCH_SAVE_REGS;
1570 *workerThreads = (gint) InterlockedCompareExchange (&async_tp.max_threads, 0, -1);
1571 *completionPortThreads = (gint) InterlockedCompareExchange (&async_io_tp.max_threads, 0, -1);
1575 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
1577 gint workers, workers_io;
1579 MONO_ARCH_SAVE_REGS;
1581 workers = (gint) InterlockedCompareExchange (&async_tp.min_threads, 0, -1);
1582 workers_io = (gint) InterlockedCompareExchange (&async_io_tp.min_threads, 0, -1);
1584 *workerThreads = workers;
1585 *completionPortThreads = workers_io;
1589 start_idle_threads (void)
1591 threadpool_start_idle_threads (&async_tp);
1595 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
1597 MONO_ARCH_SAVE_REGS;
1599 if (workerThreads < 0 || workerThreads > async_tp.max_threads)
1602 if (completionPortThreads < 0 || completionPortThreads > async_io_tp.max_threads)
1605 InterlockedExchange (&async_tp.min_threads, workerThreads);
1606 InterlockedExchange (&async_io_tp.min_threads, completionPortThreads);
1607 mono_thread_create_internal (mono_get_root_domain (), start_idle_threads, NULL, TRUE);
1612 ves_icall_System_Threading_ThreadPool_SetMaxThreads (gint workerThreads, gint completionPortThreads)
1614 MONO_ARCH_SAVE_REGS;
1616 if (workerThreads < async_tp.max_threads)
1619 /* We don't really have the concept of completion ports. Do we care here? */
1620 if (completionPortThreads < async_io_tp.max_threads)
1623 InterlockedExchange (&async_tp.max_threads, workerThreads);
1624 InterlockedExchange (&async_io_tp.max_threads, completionPortThreads);