2 * threadpool.c: global thread pool
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Gonzalo Paniagua Javier (gonzalo@ximian.com)
8 * (C) 2001-2003 Ximian, Inc.
9 * (c) 2004,2005 Novell, Inc. (http://www.novell.com)
15 #define THREADS_PER_CPU 5 /* 20 + THREADS_PER_CPU * number of CPUs */
17 #include <mono/metadata/domain-internals.h>
18 #include <mono/metadata/tabledefs.h>
19 #include <mono/metadata/threads.h>
20 #include <mono/metadata/threads-types.h>
21 #include <mono/metadata/threadpool-internals.h>
22 #include <mono/metadata/exception.h>
23 #include <mono/metadata/file-io.h>
24 #include <mono/metadata/monitor.h>
25 #include <mono/metadata/mono-mlist.h>
26 #include <mono/metadata/marshal.h>
27 #include <mono/metadata/socket-io.h>
28 #include <mono/io-layer/io-layer.h>
29 #include <mono/metadata/gc-internal.h>
30 #include <mono/utils/mono-time.h>
32 #ifdef HAVE_SYS_TIME_H
35 #include <sys/types.h>
42 #include <mono/utils/mono-poll.h>
44 #include <sys/epoll.h>
47 #include "mono/io-layer/socket-wrappers.h"
49 #include "threadpool.h"
51 #define THREAD_WANTS_A_BREAK(t) ((t->state & (ThreadState_StopRequested | \
52 ThreadState_SuspendRequested)) != 0)
56 /* maximum number of worker threads */
57 static int mono_max_worker_threads;
58 static int mono_min_worker_threads;
59 static int mono_io_max_worker_threads;
60 static int mono_io_min_worker_threads;
62 /* current number of worker threads */
63 static int mono_worker_threads = 0;
64 static int io_worker_threads = 0;
66 /* current number of busy threads */
67 static int busy_worker_threads = 0;
68 static int busy_io_worker_threads;
70 /* mono_thread_pool_init called */
73 /* we use this to store a reference to the AsyncResult to avoid GC */
74 static MonoGHashTable *ares_htable = NULL;
76 static CRITICAL_SECTION ares_lock;
77 static CRITICAL_SECTION io_queue_lock;
78 static int pending_io_items;
81 CRITICAL_SECTION io_lock; /* access to sock_to_state */
84 MonoGHashTable *sock_to_state;
86 HANDLE new_sem; /* access to newpfd and write side of the pipe */
88 gboolean epoll_disabled;
94 static SocketIOData socket_io_data;
97 static HANDLE job_added;
98 static HANDLE io_job_added;
100 /* Keep in sync with the System.MonoAsyncCall class which provides GC tracking */
103 MonoMethodMessage *msg;
104 MonoMethod *cb_method;
105 MonoDelegate *cb_target;
109 /* This is a HANDLE, we use guint64 so the managed object layout remains constant */
119 static void async_invoke_thread (gpointer data);
120 static void append_job (CRITICAL_SECTION *cs, TPQueue *list, MonoObject *ar);
121 static void start_thread_or_queue (MonoAsyncResult *ares);
122 static void mono_async_invoke (MonoAsyncResult *ares);
123 static MonoObject* dequeue_job (CRITICAL_SECTION *cs, TPQueue *list);
124 static void free_queue (TPQueue *list);
126 static TPQueue async_call_queue = {NULL, 0, 0};
127 static TPQueue async_io_queue = {NULL, 0, 0};
129 static MonoClass *async_call_klass;
130 static MonoClass *socket_async_call_klass;
131 static MonoClass *process_async_call_klass;
133 #define INIT_POLLFD(a, b, c) {(a)->fd = b; (a)->events = c; (a)->revents = 0;}
142 AIO_OP_RECV_JUST_CALLBACK,
143 AIO_OP_SEND_JUST_CALLBACK,
149 socket_io_cleanup (SocketIOData *data)
153 if (data->inited == 0)
156 EnterCriticalSection (&data->io_lock);
158 #ifdef PLATFORM_WIN32
159 closesocket (data->pipe [0]);
160 closesocket (data->pipe [1]);
162 close (data->pipe [0]);
163 close (data->pipe [1]);
168 CloseHandle (data->new_sem);
169 data->new_sem = NULL;
170 mono_g_hash_table_destroy (data->sock_to_state);
171 data->sock_to_state = NULL;
172 free_queue (&async_io_queue);
173 release = (gint) InterlockedCompareExchange (&io_worker_threads, 0, -1);
175 ReleaseSemaphore (io_job_added, release, NULL);
176 g_free (data->newpfd);
179 if (FALSE == data->epoll_disabled)
180 close (data->epollfd);
182 LeaveCriticalSection (&data->io_lock);
186 get_event_from_state (MonoSocketAsyncResult *state)
188 switch (state->operation) {
191 case AIO_OP_RECV_JUST_CALLBACK:
192 case AIO_OP_RECEIVEFROM:
193 case AIO_OP_READPIPE:
196 case AIO_OP_SEND_JUST_CALLBACK:
200 default: /* Should never happen */
201 g_print ("get_event_from_state: unknown value in switch!!!\n");
207 get_events_from_list (MonoMList *list)
209 MonoSocketAsyncResult *state;
212 while (list && (state = (MonoSocketAsyncResult *)mono_mlist_get_data (list))) {
213 events |= get_event_from_state (state);
214 list = mono_mlist_next (list);
220 #define ICALL_RECV(x) ves_icall_System_Net_Sockets_Socket_Receive_internal (\
221 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
222 x->socket_flags, &x->error);
224 #define ICALL_SEND(x) ves_icall_System_Net_Sockets_Socket_Send_internal (\
225 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
226 x->socket_flags, &x->error);
229 async_invoke_io_thread (gpointer data)
233 thread = mono_thread_current ();
234 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
237 MonoSocketAsyncResult *state;
240 state = (MonoSocketAsyncResult *) data;
242 InterlockedDecrement (&pending_io_items);
244 switch (state->operation) {
246 state->total = ICALL_RECV (state);
249 state->total = ICALL_SEND (state);
253 /* worker threads invokes methods in different domains,
254 * so we need to set the right domain here */
255 domain = ((MonoObject *)ar)->vtable->domain;
256 mono_thread_push_appdomain_ref (domain);
257 if (mono_domain_set (domain, FALSE)) {
260 mono_async_invoke (ar);
261 ac = (ASyncCall *) ar->object_data;
263 if (ac->msg->exc != NULL)
264 mono_unhandled_exception (ac->msg->exc);
266 mono_domain_set (mono_get_root_domain (), TRUE);
268 mono_thread_pop_appdomain_ref ();
269 InterlockedDecrement (&busy_io_worker_threads);
272 data = dequeue_job (&io_queue_lock, &async_io_queue);
277 guint32 start_time = mono_msec_ticks ();
280 wr = WaitForSingleObjectEx (io_job_added, (guint32)timeout, TRUE);
281 if (THREAD_WANTS_A_BREAK (thread))
282 mono_thread_interruption_checkpoint ();
284 timeout -= mono_msec_ticks () - start_time;
286 if (wr != WAIT_TIMEOUT)
287 data = dequeue_job (&io_queue_lock, &async_io_queue);
289 while (!data && timeout > 0);
293 if (InterlockedDecrement (&io_worker_threads) < 2) {
294 /* If we have pending items, keep the thread alive */
295 if (InterlockedCompareExchange (&pending_io_items, 0, 0) != 0) {
296 InterlockedIncrement (&io_worker_threads);
303 InterlockedIncrement (&busy_io_worker_threads);
306 g_assert_not_reached ();
310 start_io_thread_or_queue (MonoSocketAsyncResult *ares)
315 busy = (int) InterlockedCompareExchange (&busy_io_worker_threads, 0, -1);
316 worker = (int) InterlockedCompareExchange (&io_worker_threads, 0, -1);
317 if (worker <= ++busy &&
318 worker < mono_io_max_worker_threads) {
319 InterlockedIncrement (&busy_io_worker_threads);
320 InterlockedIncrement (&io_worker_threads);
321 domain = ((ares) ? ((MonoObject *) ares)->vtable->domain : mono_domain_get ());
322 mono_thread_create_internal (mono_get_root_domain (), async_invoke_io_thread, ares, TRUE);
324 append_job (&io_queue_lock, &async_io_queue, (MonoObject*)ares);
325 ReleaseSemaphore (io_job_added, 1, NULL);
330 process_io_event (MonoMList *list, int event)
332 MonoSocketAsyncResult *state;
338 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
339 if (get_event_from_state (state) == event)
342 list = mono_mlist_next (list);
346 oldlist = mono_mlist_remove_item (oldlist, list);
348 g_print ("Dispatching event %d on socket %d\n", event, state->handle);
350 InterlockedIncrement (&pending_io_items);
351 start_io_thread_or_queue (state);
358 mark_bad_fds (mono_pollfd *pfds, int nfds)
364 for (i = 0; i < nfds; i++) {
369 ret = mono_poll (pfd, 1, 0);
370 if (ret == -1 && errno == EBADF) {
371 pfd->revents |= MONO_POLLNVAL;
373 } else if (ret == 1) {
382 socket_io_poll_main (gpointer p)
384 #define INITIAL_POLLFD_SIZE 1024
385 #define POLL_ERRORS (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL)
386 SocketIOData *data = p;
393 thread = mono_thread_current ();
394 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
396 allocated = INITIAL_POLLFD_SIZE;
397 pfds = g_new0 (mono_pollfd, allocated);
398 INIT_POLLFD (pfds, data->pipe [0], MONO_POLLIN);
399 for (i = 1; i < allocated; i++)
400 INIT_POLLFD (&pfds [i], -1, 0);
410 if (THREAD_WANTS_A_BREAK (thread))
411 mono_thread_interruption_checkpoint ();
414 nsock = mono_poll (pfds, maxfd, -1);
415 } while (nsock == -1 && errno == EINTR);
418 * Apart from EINTR, we only check EBADF, for the rest:
419 * EINVAL: mono_poll() 'protects' us from descriptor
420 * numbers above the limit if using select() by marking
421 * then as MONO_POLLERR. If a system poll() is being
422 * used, the number of descriptor we're passing will not
423 * be over sysconf(_SC_OPEN_MAX), as the error would have
424 * happened when opening.
426 * EFAULT: we own the memory pointed by pfds.
427 * ENOMEM: we're doomed anyway
431 if (nsock == -1 && errno == EBADF) {
432 pfds->revents = 0; /* Just in case... */
433 nsock = mark_bad_fds (pfds, maxfd);
436 if ((pfds->revents & POLL_ERRORS) != 0) {
437 /* We're supposed to die now, as the pipe has been closed */
439 socket_io_cleanup (data);
443 /* Got a new socket */
444 if ((pfds->revents & MONO_POLLIN) != 0) {
447 for (i = 1; i < allocated; i++) {
449 if (pfd->fd == -1 || pfd->fd == data->newpfd->fd)
453 if (i == allocated) {
458 allocated = allocated * 2;
459 pfds = g_renew (mono_pollfd, oldfd, allocated);
461 for (; i < allocated; i++)
462 INIT_POLLFD (&pfds [i], -1, 0);
464 #ifndef PLATFORM_WIN32
465 nread = read (data->pipe [0], one, 1);
467 nread = recv ((SOCKET) data->pipe [0], one, 1, 0);
471 return; /* we're closed */
474 INIT_POLLFD (&pfds [i], data->newpfd->fd, data->newpfd->events);
475 ReleaseSemaphore (data->new_sem, 1, NULL);
484 EnterCriticalSection (&data->io_lock);
485 if (data->inited == 0) {
487 LeaveCriticalSection (&data->io_lock);
488 return; /* cleanup called */
491 for (i = 1; i < maxfd && nsock > 0; i++) {
493 if (pfd->fd == -1 || pfd->revents == 0)
497 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
498 if (list != NULL && (pfd->revents & (MONO_POLLIN | POLL_ERRORS)) != 0) {
499 list = process_io_event (list, MONO_POLLIN);
502 if (list != NULL && (pfd->revents & (MONO_POLLOUT | POLL_ERRORS)) != 0) {
503 list = process_io_event (list, MONO_POLLOUT);
507 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (pfd->fd), list);
508 pfd->events = get_events_from_list (list);
510 mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
516 LeaveCriticalSection (&data->io_lock);
521 #define EPOLL_ERRORS (EPOLLERR | EPOLLHUP)
523 socket_io_epoll_main (gpointer p)
528 struct epoll_event *events, *evt;
529 const int nevents = 512;
533 epollfd = data->epollfd;
534 thread = mono_thread_current ();
535 thread->threadpool_thread = TRUE;
536 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
537 events = g_new0 (struct epoll_event, nevents);
542 if (THREAD_WANTS_A_BREAK (thread))
543 mono_thread_interruption_checkpoint ();
546 g_print ("epoll_wait init\n");
548 ready = epoll_wait (epollfd, events, nevents, -1);
552 g_print ("epoll_wait end with %d ready sockets (%d %s).\n", ready, err, (err) ? g_strerror (err) : "");
556 } while (ready == -1 && errno == EINTR);
562 g_warning ("epoll_wait: %d %s\n", err, g_strerror (err));
568 EnterCriticalSection (&data->io_lock);
569 if (data->inited == 0) {
571 g_print ("data->inited == 0\n");
575 return; /* cleanup called */
578 for (i = 0; i < ready; i++) {
584 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
586 g_print ("Event %d on %d list length: %d\n", evt->events, fd, mono_mlist_length (list));
588 if (list != NULL && (evt->events & (EPOLLIN | EPOLL_ERRORS)) != 0) {
589 list = process_io_event (list, MONO_POLLIN);
592 if (list != NULL && (evt->events & (EPOLLOUT | EPOLL_ERRORS)) != 0) {
593 list = process_io_event (list, MONO_POLLOUT);
597 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (fd), list);
598 evt->events = get_events_from_list (list);
600 g_print ("MOD %d to %d\n", fd, evt->events);
602 if (epoll_ctl (epollfd, EPOLL_CTL_MOD, fd, evt)) {
603 if (epoll_ctl (epollfd, EPOLL_CTL_ADD, fd, evt) == -1) {
606 g_message ("epoll_ctl(MOD): %d %s fd: %d events: %d", err, g_strerror (err), fd, evt->events);
612 mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (fd));
614 g_print ("DEL %d\n", fd);
616 epoll_ctl (epollfd, EPOLL_CTL_DEL, fd, evt);
619 LeaveCriticalSection (&data->io_lock);
625 * select/poll wake up when a socket is closed, but epoll just removes
626 * the socket from its internal list without notification.
629 mono_thread_pool_remove_socket (int sock)
631 MonoMList *list, *next;
632 MonoSocketAsyncResult *state;
634 if (socket_io_data.inited == FALSE)
637 EnterCriticalSection (&socket_io_data.io_lock);
638 list = mono_g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
640 mono_g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
642 LeaveCriticalSection (&socket_io_data.io_lock);
645 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
646 if (state->operation == AIO_OP_RECEIVE)
647 state->operation = AIO_OP_RECV_JUST_CALLBACK;
648 else if (state->operation == AIO_OP_SEND)
649 state->operation = AIO_OP_SEND_JUST_CALLBACK;
651 next = mono_mlist_remove_item (list, list);
652 list = process_io_event (list, MONO_POLLIN);
654 process_io_event (list, MONO_POLLOUT);
660 #ifdef PLATFORM_WIN32
662 connect_hack (gpointer x)
664 struct sockaddr_in *addr = (struct sockaddr_in *) x;
667 while (connect ((SOCKET) socket_io_data.pipe [1], (SOCKADDR *) addr, sizeof (struct sockaddr_in))) {
670 g_warning ("Error initializing async. sockets %d.\n", WSAGetLastError ());
671 g_assert (WSAGetLastError ());
678 socket_io_init (SocketIOData *data)
680 #ifdef PLATFORM_WIN32
681 struct sockaddr_in server;
682 struct sockaddr_in client;
688 inited = InterlockedCompareExchange (&data->inited, -1, -1);
692 EnterCriticalSection (&data->io_lock);
693 inited = InterlockedCompareExchange (&data->inited, -1, -1);
695 LeaveCriticalSection (&data->io_lock);
700 data->epoll_disabled = (g_getenv ("MONO_DISABLE_AIO") != NULL);
701 if (FALSE == data->epoll_disabled) {
702 data->epollfd = epoll_create (256);
703 data->epoll_disabled = (data->epollfd == -1);
704 if (data->epoll_disabled && g_getenv ("MONO_DEBUG"))
705 g_message ("epoll_create() failed. Using plain poll().");
710 data->epoll_disabled = TRUE;
713 #ifndef PLATFORM_WIN32
714 if (data->epoll_disabled) {
715 if (pipe (data->pipe) != 0) {
725 srv = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
726 g_assert (srv != INVALID_SOCKET);
727 data->pipe [1] = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
728 g_assert (data->pipe [1] != INVALID_SOCKET);
730 server.sin_family = AF_INET;
731 server.sin_addr.s_addr = inet_addr ("127.0.0.1");
733 if (bind (srv, (SOCKADDR *) &server, sizeof (server))) {
734 g_print ("%d\n", WSAGetLastError ());
738 len = sizeof (server);
739 getsockname (srv, (SOCKADDR *) &server, &len);
741 mono_thread_create (mono_get_root_domain (), connect_hack, &server);
742 len = sizeof (server);
743 data->pipe [0] = accept (srv, (SOCKADDR *) &client, &len);
744 g_assert (data->pipe [0] != INVALID_SOCKET);
747 mono_io_max_worker_threads = mono_max_worker_threads / 2;
748 if (mono_io_max_worker_threads < 10)
749 mono_io_max_worker_threads = 10;
751 data->sock_to_state = mono_g_hash_table_new_type (g_direct_hash, g_direct_equal, MONO_HASH_VALUE_GC);
753 if (data->epoll_disabled) {
754 data->new_sem = CreateSemaphore (NULL, 1, 1, NULL);
755 g_assert (data->new_sem != NULL);
757 io_job_added = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
758 g_assert (io_job_added != NULL);
759 InitializeCriticalSection (&io_queue_lock);
760 if (data->epoll_disabled) {
761 mono_thread_create_internal (mono_get_root_domain (), socket_io_poll_main, data, TRUE);
765 mono_thread_create_internal (mono_get_root_domain (), socket_io_epoll_main, data, TRUE);
768 InterlockedCompareExchange (&data->inited, 1, 0);
769 LeaveCriticalSection (&data->io_lock);
773 socket_io_add_poll (MonoSocketAsyncResult *state)
778 SocketIOData *data = &socket_io_data;
780 #if defined(PLATFORM_MACOSX) || defined(PLATFORM_BSD6) || defined(PLATFORM_WIN32) || defined(PLATFORM_SOLARIS)
781 /* select() for connect() does not work well on the Mac. Bug #75436. */
782 /* Bug #77637 for the BSD 6 case */
783 /* Bug #78888 for the Windows case */
784 if (state->operation == AIO_OP_CONNECT && state->blocking == TRUE) {
785 start_io_thread_or_queue (state);
789 WaitForSingleObject (data->new_sem, INFINITE);
790 if (data->newpfd == NULL)
791 data->newpfd = g_new0 (mono_pollfd, 1);
793 EnterCriticalSection (&data->io_lock);
794 /* FIXME: 64 bit issue: handle can be a pointer on windows? */
795 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (state->handle));
797 list = mono_mlist_alloc ((MonoObject*)state);
799 list = mono_mlist_append (list, (MonoObject*)state);
802 events = get_events_from_list (list);
803 INIT_POLLFD (data->newpfd, GPOINTER_TO_INT (state->handle), events);
804 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (state->handle), list);
805 LeaveCriticalSection (&data->io_lock);
806 *msg = (char) state->operation;
807 #ifndef PLATFORM_WIN32
808 write (data->pipe [1], msg, 1);
810 send ((SOCKET) data->pipe [1], msg, 1, 0);
816 socket_io_add_epoll (MonoSocketAsyncResult *state)
819 SocketIOData *data = &socket_io_data;
820 struct epoll_event event;
824 memset (&event, 0, sizeof (struct epoll_event));
825 fd = GPOINTER_TO_INT (state->handle);
826 EnterCriticalSection (&data->io_lock);
827 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
829 list = mono_mlist_alloc ((MonoObject*)state);
830 epoll_op = EPOLL_CTL_ADD;
832 list = mono_mlist_append (list, (MonoObject*)state);
833 epoll_op = EPOLL_CTL_MOD;
836 ievt = get_events_from_list (list);
837 if ((ievt & MONO_POLLIN) != 0)
838 event.events |= EPOLLIN;
839 if ((ievt & MONO_POLLOUT) != 0)
840 event.events |= EPOLLOUT;
842 mono_g_hash_table_replace (data->sock_to_state, state->handle, list);
845 g_print ("%s %d with %d\n", epoll_op == EPOLL_CTL_ADD ? "ADD" : "MOD", fd, event.events);
847 if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
849 if (epoll_op == EPOLL_CTL_ADD && err == EEXIST) {
850 epoll_op = EPOLL_CTL_MOD;
851 if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
852 g_message ("epoll_ctl(MOD): %d %s\n", err, g_strerror (err));
857 LeaveCriticalSection (&data->io_lock);
863 socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
865 socket_io_init (&socket_io_data);
866 MONO_OBJECT_SETREF (state, ares, ares);
868 if (socket_io_data.epoll_disabled == FALSE) {
869 if (socket_io_add_epoll (state))
873 socket_io_add_poll (state);
877 socket_io_filter (MonoObject *target, MonoObject *state)
880 MonoSocketAsyncResult *sock_res = (MonoSocketAsyncResult *) state;
883 if (target == NULL || state == NULL)
886 if (socket_async_call_klass == NULL) {
887 klass = target->vtable->klass;
888 /* Check if it's SocketAsyncCall in System.Net.Sockets
889 * FIXME: check the assembly is signed correctly for extra care
891 if (klass->name [0] == 'S' && strcmp (klass->name, "SocketAsyncCall") == 0
892 && strcmp (mono_image_get_name (klass->image), "System") == 0
893 && klass->nested_in && strcmp (klass->nested_in->name, "Socket") == 0)
894 socket_async_call_klass = klass;
897 if (process_async_call_klass == NULL) {
898 klass = target->vtable->klass;
899 /* Check if it's AsyncReadHandler in System.Diagnostics.Process
900 * FIXME: check the assembly is signed correctly for extra care
902 if (klass->name [0] == 'A' && strcmp (klass->name, "AsyncReadHandler") == 0
903 && strcmp (mono_image_get_name (klass->image), "System") == 0
904 && klass->nested_in && strcmp (klass->nested_in->name, "Process") == 0)
905 process_async_call_klass = klass;
907 /* return both when socket_async_call_klass has not been seen yet and when
908 * the object is not an instance of the class.
910 if (target->vtable->klass != socket_async_call_klass && target->vtable->klass != process_async_call_klass)
913 op = sock_res->operation;
914 if (op < AIO_OP_FIRST || op >= AIO_OP_LAST)
921 mono_async_invoke (MonoAsyncResult *ares)
923 ASyncCall *ac = (ASyncCall *)ares->object_data;
924 MonoThread *thread = NULL;
925 MonoObject *res, *exc = NULL;
926 MonoArray *out_args = NULL;
928 if (ares->execution_context) {
929 /* use captured ExecutionContext (if available) */
930 thread = mono_thread_current ();
931 MONO_OBJECT_SETREF (ares, original_context, thread->execution_context);
932 MONO_OBJECT_SETREF (thread, execution_context, ares->execution_context);
934 ares->original_context = NULL;
938 res = mono_message_invoke (ares->async_delegate, ac->msg, &exc, &out_args);
939 MONO_OBJECT_SETREF (ac, res, res);
940 MONO_OBJECT_SETREF (ac, msg->exc, exc);
941 MONO_OBJECT_SETREF (ac, out_args, out_args);
945 /* call async callback if cb_method != null*/
947 MonoObject *exc = NULL;
949 mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &exc);
950 /* 'exc' will be the previous ac->msg->exc if not NULL and not
951 * catched. If catched, this will be set to NULL and the
952 * exception will not be printed. */
953 MONO_OBJECT_SETREF (ac->msg, exc, exc);
956 /* restore original thread execution context if flow isn't suppressed, i.e. non null */
957 if (ares->original_context) {
958 MONO_OBJECT_SETREF (thread, execution_context, ares->original_context);
959 ares->original_context = NULL;
962 /* notify listeners */
963 mono_monitor_enter ((MonoObject *) ares);
964 if (ares->handle != NULL) {
965 ac->wait_event = (gsize) mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
966 SetEvent ((gpointer)(gsize)ac->wait_event);
968 mono_monitor_exit ((MonoObject *) ares);
970 EnterCriticalSection (&ares_lock);
971 mono_g_hash_table_remove (ares_htable, ares);
972 LeaveCriticalSection (&ares_lock);
976 mono_thread_pool_init ()
979 int threads_per_cpu = THREADS_PER_CPU;
981 if ((int) InterlockedCompareExchange (&tp_inited, 1, 0) == 1)
984 MONO_GC_REGISTER_ROOT (ares_htable);
985 MONO_GC_REGISTER_ROOT (socket_io_data.sock_to_state);
986 InitializeCriticalSection (&socket_io_data.io_lock);
987 InitializeCriticalSection (&ares_lock);
988 ares_htable = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_VALUE_GC);
989 job_added = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
990 g_assert (job_added != NULL);
991 GetSystemInfo (&info);
992 if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
993 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
994 if (threads_per_cpu <= 0)
995 threads_per_cpu = THREADS_PER_CPU;
998 mono_max_worker_threads = 20 + threads_per_cpu * info.dwNumberOfProcessors;
1000 async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
1001 g_assert (async_call_klass);
1005 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
1008 MonoDomain *domain = mono_domain_get ();
1009 MonoAsyncResult *ares;
1012 ac = (ASyncCall*)mono_object_new (mono_domain_get (), async_call_klass);
1013 MONO_OBJECT_SETREF (ac, msg, msg);
1014 MONO_OBJECT_SETREF (ac, state, state);
1016 if (async_callback) {
1017 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
1018 MONO_OBJECT_SETREF (ac, cb_target, async_callback);
1021 ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
1022 MONO_OBJECT_SETREF (ares, async_delegate, target);
1024 EnterCriticalSection (&ares_lock);
1025 mono_g_hash_table_insert (ares_htable, ares, ares);
1026 LeaveCriticalSection (&ares_lock);
1028 if (socket_io_filter (target, state)) {
1029 socket_io_add (ares, (MonoSocketAsyncResult *) state);
1033 start_thread_or_queue (ares);
1038 start_thread_or_queue (MonoAsyncResult *ares)
1042 busy = (int) InterlockedCompareExchange (&busy_worker_threads, 0, -1);
1043 worker = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1044 if (worker <= ++busy &&
1045 worker < mono_max_worker_threads) {
1046 InterlockedIncrement (&mono_worker_threads);
1047 InterlockedIncrement (&busy_worker_threads);
1048 mono_thread_create_internal (mono_get_root_domain (), async_invoke_thread, ares, TRUE);
1050 append_job (&mono_delegate_section, &async_call_queue, (MonoObject*)ares);
1051 ReleaseSemaphore (job_added, 1, NULL);
1056 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1063 /* check if already finished */
1064 mono_monitor_enter ((MonoObject *) ares);
1066 if (ares->endinvoke_called) {
1067 *exc = (MonoObject *)mono_exception_from_name (mono_defaults.corlib, "System",
1068 "InvalidOperationException");
1069 mono_monitor_exit ((MonoObject *) ares);
1073 ares->endinvoke_called = 1;
1074 ac = (ASyncCall *)ares->object_data;
1076 g_assert (ac != NULL);
1078 /* wait until we are really finished */
1079 if (!ares->completed) {
1080 if (ares->handle == NULL) {
1081 ac->wait_event = (gsize)CreateEvent (NULL, TRUE, FALSE, NULL);
1082 g_assert(ac->wait_event != 0);
1083 MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), (gpointer)(gsize)ac->wait_event));
1085 mono_monitor_exit ((MonoObject *) ares);
1086 WaitForSingleObjectEx ((gpointer)(gsize)ac->wait_event, INFINITE, TRUE);
1088 mono_monitor_exit ((MonoObject *) ares);
1091 *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1092 *out_args = ac->out_args;
1098 mono_thread_pool_cleanup (void)
1102 EnterCriticalSection (&mono_delegate_section);
1103 free_queue (&async_call_queue);
1104 release = (gint) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1105 LeaveCriticalSection (&mono_delegate_section);
1107 ReleaseSemaphore (job_added, release, NULL);
1109 socket_io_cleanup (&socket_io_data);
1113 append_job (CRITICAL_SECTION *cs, TPQueue *list, MonoObject *ar)
1115 EnterCriticalSection (cs);
1116 if (list->array && (list->next_elem < mono_array_length (list->array))) {
1117 mono_array_setref (list->array, list->next_elem, ar);
1119 LeaveCriticalSection (cs);
1123 MONO_GC_REGISTER_ROOT (list->array);
1124 list->array = mono_array_new (mono_get_root_domain (), mono_defaults.object_class, 16);
1126 int count = list->next_elem - list->first_elem;
1127 /* slide the array or create a larger one if it's full */
1128 if (list->first_elem) {
1129 mono_array_memcpy_refs (list->array, 0, list->array, list->first_elem, count);
1131 MonoArray *newa = mono_array_new (mono_get_root_domain (), mono_defaults.object_class, mono_array_length (list->array) * 2);
1132 mono_array_memcpy_refs (newa, 0, list->array, list->first_elem, count);
1135 list->first_elem = 0;
1136 list->next_elem = count;
1138 mono_array_setref (list->array, list->next_elem, ar);
1140 LeaveCriticalSection (cs);
1144 dequeue_job (CRITICAL_SECTION *cs, TPQueue *list)
1149 EnterCriticalSection (cs);
1150 if (!list->array || list->first_elem == list->next_elem) {
1151 LeaveCriticalSection (cs);
1154 ar = mono_array_get (list->array, MonoObject*, list->first_elem);
1156 count = list->next_elem - list->first_elem;
1157 /* reduce the size of the array if it's mostly empty */
1158 if (mono_array_length (list->array) > 16 && count < (mono_array_length (list->array) / 3)) {
1159 MonoArray *newa = mono_array_new (mono_get_root_domain (), mono_defaults.object_class, mono_array_length (list->array) / 2);
1160 mono_array_memcpy_refs (newa, 0, list->array, list->first_elem, count);
1162 list->first_elem = 0;
1163 list->next_elem = count;
1165 LeaveCriticalSection (cs);
1171 free_queue (TPQueue *list)
1174 list->first_elem = list->next_elem = 0;
1178 async_invoke_thread (gpointer data)
1184 thread = mono_thread_current ();
1185 thread->threadpool_thread = TRUE;
1186 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
1189 MonoAsyncResult *ar;
1191 ar = (MonoAsyncResult *) data;
1193 /* worker threads invokes methods in different domains,
1194 * so we need to set the right domain here */
1195 domain = ((MonoObject *)ar)->vtable->domain;
1196 mono_thread_push_appdomain_ref (domain);
1197 if (mono_domain_set (domain, FALSE)) {
1200 mono_async_invoke (ar);
1201 ac = (ASyncCall *) ar->object_data;
1203 if (ac->msg->exc != NULL)
1204 mono_unhandled_exception (ac->msg->exc);
1206 mono_domain_set (mono_get_root_domain (), TRUE);
1208 mono_thread_pop_appdomain_ref ();
1209 InterlockedDecrement (&busy_worker_threads);
1212 data = dequeue_job (&mono_delegate_section, &async_call_queue);
1216 int timeout = 10000;
1217 guint32 start_time = mono_msec_ticks ();
1220 wr = WaitForSingleObjectEx (job_added, (guint32)timeout, TRUE);
1221 if (THREAD_WANTS_A_BREAK (thread))
1222 mono_thread_interruption_checkpoint ();
1224 timeout -= mono_msec_ticks () - start_time;
1226 if (wr != WAIT_TIMEOUT)
1227 data = dequeue_job (&mono_delegate_section, &async_call_queue);
1229 while (!data && timeout > 0);
1233 workers = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1234 min = (int) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
1236 while (!data && workers <= min) {
1237 WaitForSingleObjectEx (job_added, INFINITE, TRUE);
1238 if (THREAD_WANTS_A_BREAK (thread))
1239 mono_thread_interruption_checkpoint ();
1241 data = dequeue_job (&mono_delegate_section, &async_call_queue);
1242 workers = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1243 min = (int) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
1248 InterlockedDecrement (&mono_worker_threads);
1252 InterlockedIncrement (&busy_worker_threads);
1255 g_assert_not_reached ();
1259 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
1263 MONO_ARCH_SAVE_REGS;
1265 busy = (gint) InterlockedCompareExchange (&busy_worker_threads, 0, -1);
1266 busy_io = (gint) InterlockedCompareExchange (&busy_io_worker_threads, 0, -1);
1267 *workerThreads = mono_max_worker_threads - busy;
1268 *completionPortThreads = mono_io_max_worker_threads - busy_io;
1272 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
1274 MONO_ARCH_SAVE_REGS;
1276 *workerThreads = mono_max_worker_threads;
1277 *completionPortThreads = mono_io_max_worker_threads;
1281 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
1283 gint workers, workers_io;
1285 MONO_ARCH_SAVE_REGS;
1287 workers = (gint) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
1288 workers_io = (gint) InterlockedCompareExchange (&mono_io_min_worker_threads, 0, -1);
1290 *workerThreads = workers;
1291 *completionPortThreads = workers_io;
1295 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
1297 MONO_ARCH_SAVE_REGS;
1299 if (workerThreads < 0 || workerThreads > mono_max_worker_threads)
1302 if (completionPortThreads < 0 || completionPortThreads > mono_io_max_worker_threads)
1305 InterlockedExchange (&mono_min_worker_threads, workerThreads);
1306 InterlockedExchange (&mono_io_min_worker_threads, completionPortThreads);
1307 /* FIXME: should actually start the idle threads if needed */
1312 ves_icall_System_Threading_ThreadPool_SetMaxThreads (gint workerThreads, gint completionPortThreads)
1314 MONO_ARCH_SAVE_REGS;
1316 if (workerThreads < mono_max_worker_threads)
1319 if (completionPortThreads < mono_io_max_worker_threads)
1322 InterlockedExchange (&mono_max_worker_threads, workerThreads);
1323 InterlockedExchange (&mono_io_max_worker_threads, completionPortThreads);