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)
17 #define _WIN32_WINNT 0x0500
20 #define THREADS_PER_CPU 5 /* 20 + THREADS_PER_CPU * number of CPUs */
22 #include <mono/metadata/domain-internals.h>
23 #include <mono/metadata/tabledefs.h>
24 #include <mono/metadata/threads.h>
25 #include <mono/metadata/threads-types.h>
26 #include <mono/metadata/threadpool-internals.h>
27 #include <mono/metadata/exception.h>
28 #include <mono/metadata/file-io.h>
29 #include <mono/metadata/monitor.h>
30 #include <mono/metadata/mono-mlist.h>
31 #include <mono/metadata/marshal.h>
32 #include <mono/metadata/socket-io.h>
33 #include <mono/io-layer/io-layer.h>
34 #include <mono/os/gc_wrapper.h>
36 #ifdef HAVE_SYS_TIME_H
39 #include <sys/types.h>
46 #include <mono/utils/mono-poll.h>
48 #include <sys/epoll.h>
51 #include "mono/io-layer/socket-wrappers.h"
53 #include "threadpool.h"
55 #define THREAD_WANTS_A_BREAK(t) ((t->state & (ThreadState_StopRequested | \
56 ThreadState_SuspendRequested)) != 0)
60 /* maximum number of worker threads */
61 static int mono_max_worker_threads;
62 static int mono_min_worker_threads;
63 static int mono_io_max_worker_threads;
64 static int mono_io_min_worker_threads;
66 /* current number of worker threads */
67 static int mono_worker_threads = 0;
68 static int io_worker_threads = 0;
70 /* current number of busy threads */
71 static int busy_worker_threads = 0;
72 static int busy_io_worker_threads;
74 /* mono_thread_pool_init called */
77 /* we use this to store a reference to the AsyncResult to avoid GC */
78 static MonoGHashTable *ares_htable = NULL;
80 static CRITICAL_SECTION ares_lock;
81 static CRITICAL_SECTION io_queue_lock;
82 static int pending_io_items;
85 CRITICAL_SECTION io_lock; /* access to sock_to_state */
88 MonoGHashTable *sock_to_state;
90 HANDLE new_sem; /* access to newpfd and write side of the pipe */
92 gboolean epoll_disabled;
98 static SocketIOData socket_io_data;
100 /* we append a job */
101 static HANDLE job_added;
102 static HANDLE io_job_added;
104 /* Keep in sync with the System.MonoAsyncCall class which provides GC tracking */
107 MonoMethodMessage *msg;
108 MonoMethod *cb_method;
109 MonoDelegate *cb_target;
113 /* This is a HANDLE, we use guint64 so the managed object layout remains constant */
123 static void async_invoke_thread (gpointer data);
124 static void append_job (CRITICAL_SECTION *cs, TPQueue *list, MonoObject *ar);
125 static void start_thread_or_queue (MonoAsyncResult *ares);
126 static void mono_async_invoke (MonoAsyncResult *ares);
127 static MonoObject* dequeue_job (CRITICAL_SECTION *cs, TPQueue *list);
128 static void free_queue (TPQueue *list);
130 static TPQueue async_call_queue = {NULL, 0, 0};
131 static TPQueue async_io_queue = {NULL, 0, 0};
133 static MonoClass *async_call_klass;
134 static MonoClass *socket_async_call_klass;
135 static MonoClass *process_async_call_klass;
137 #define INIT_POLLFD(a, b, c) {(a)->fd = b; (a)->events = c; (a)->revents = 0;}
146 AIO_OP_RECV_JUST_CALLBACK,
147 AIO_OP_SEND_JUST_CALLBACK,
153 socket_io_cleanup (SocketIOData *data)
157 if (data->inited == 0)
160 EnterCriticalSection (&data->io_lock);
162 #ifdef PLATFORM_WIN32
163 closesocket (data->pipe [0]);
164 closesocket (data->pipe [1]);
166 close (data->pipe [0]);
167 close (data->pipe [1]);
172 CloseHandle (data->new_sem);
173 data->new_sem = NULL;
174 mono_g_hash_table_destroy (data->sock_to_state);
175 data->sock_to_state = NULL;
176 free_queue (&async_io_queue);
177 release = (gint) InterlockedCompareExchange (&io_worker_threads, 0, -1);
179 ReleaseSemaphore (io_job_added, release, NULL);
180 g_free (data->newpfd);
183 if (FALSE == data->epoll_disabled)
184 close (data->epollfd);
186 LeaveCriticalSection (&data->io_lock);
190 get_event_from_state (MonoSocketAsyncResult *state)
192 switch (state->operation) {
195 case AIO_OP_RECV_JUST_CALLBACK:
196 case AIO_OP_RECEIVEFROM:
197 case AIO_OP_READPIPE:
200 case AIO_OP_SEND_JUST_CALLBACK:
204 default: /* Should never happen */
205 g_print ("get_event_from_state: unknown value in switch!!!\n");
211 get_events_from_list (MonoMList *list)
213 MonoSocketAsyncResult *state;
216 while (list && (state = (MonoSocketAsyncResult *)mono_mlist_get_data (list))) {
217 events |= get_event_from_state (state);
218 list = mono_mlist_next (list);
224 #define ICALL_RECV(x) ves_icall_System_Net_Sockets_Socket_Receive_internal (\
225 (SOCKET) x->handle, x->buffer, x->offset, x->size,\
226 x->socket_flags, &x->error);
228 #define ICALL_SEND(x) ves_icall_System_Net_Sockets_Socket_Send_internal (\
229 (SOCKET) x->handle, x->buffer, x->offset, x->size,\
230 x->socket_flags, &x->error);
233 async_invoke_io_thread (gpointer data)
237 thread = mono_thread_current ();
238 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
241 MonoSocketAsyncResult *state;
244 state = (MonoSocketAsyncResult *) data;
246 InterlockedDecrement (&pending_io_items);
248 switch (state->operation) {
250 state->total = ICALL_RECV (state);
253 state->total = ICALL_SEND (state);
257 /* worker threads invokes methods in different domains,
258 * so we need to set the right domain here */
259 domain = ((MonoObject *)ar)->vtable->domain;
260 mono_thread_push_appdomain_ref (domain);
261 if (mono_domain_set (domain, FALSE)) {
264 mono_async_invoke (ar);
265 ac = (ASyncCall *) ar->object_data;
267 if (ac->msg->exc != NULL)
268 mono_unhandled_exception (ac->msg->exc);
270 mono_domain_set (mono_get_root_domain (), TRUE);
272 mono_thread_pop_appdomain_ref ();
273 InterlockedDecrement (&busy_io_worker_threads);
276 data = dequeue_job (&io_queue_lock, &async_io_queue);
281 guint32 start_time = GetTickCount ();
284 wr = WaitForSingleObjectEx (io_job_added, (guint32)timeout, TRUE);
285 if (THREAD_WANTS_A_BREAK (thread))
286 mono_thread_interruption_checkpoint ();
288 timeout -= GetTickCount () - start_time;
290 if (wr != WAIT_TIMEOUT)
291 data = dequeue_job (&io_queue_lock, &async_io_queue);
293 while (!data && timeout > 0);
297 if (InterlockedDecrement (&io_worker_threads) < 2) {
298 /* If we have pending items, keep the thread alive */
299 if (InterlockedCompareExchange (&pending_io_items, 0, 0) != 0) {
300 InterlockedIncrement (&io_worker_threads);
307 InterlockedIncrement (&busy_io_worker_threads);
310 g_assert_not_reached ();
314 start_io_thread_or_queue (MonoSocketAsyncResult *ares)
319 busy = (int) InterlockedCompareExchange (&busy_io_worker_threads, 0, -1);
320 worker = (int) InterlockedCompareExchange (&io_worker_threads, 0, -1);
321 if (worker <= ++busy &&
322 worker < mono_io_max_worker_threads) {
323 InterlockedIncrement (&busy_io_worker_threads);
324 InterlockedIncrement (&io_worker_threads);
325 domain = ((ares) ? ((MonoObject *) ares)->vtable->domain : mono_domain_get ());
326 mono_thread_create_internal (mono_get_root_domain (), async_invoke_io_thread, ares, TRUE);
328 append_job (&io_queue_lock, &async_io_queue, (MonoObject*)ares);
329 ReleaseSemaphore (io_job_added, 1, NULL);
334 process_io_event (MonoMList *list, int event)
336 MonoSocketAsyncResult *state;
342 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
343 if (get_event_from_state (state) == event)
346 list = mono_mlist_next (list);
350 oldlist = mono_mlist_remove_item (oldlist, list);
352 g_print ("Dispatching event %d on socket %d\n", event, state->handle);
354 InterlockedIncrement (&pending_io_items);
355 start_io_thread_or_queue (state);
362 mark_bad_fds (mono_pollfd *pfds, int nfds)
368 for (i = 0; i < nfds; i++) {
373 ret = mono_poll (pfd, 1, 0);
374 if (ret == -1 && errno == EBADF) {
375 pfd->revents |= MONO_POLLNVAL;
377 } else if (ret == 1) {
386 socket_io_poll_main (gpointer p)
388 #define INITIAL_POLLFD_SIZE 1024
389 #define POLL_ERRORS (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL)
390 SocketIOData *data = p;
397 thread = mono_thread_current ();
398 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
400 allocated = INITIAL_POLLFD_SIZE;
401 pfds = g_new0 (mono_pollfd, allocated);
402 INIT_POLLFD (pfds, data->pipe [0], MONO_POLLIN);
403 for (i = 1; i < allocated; i++)
404 INIT_POLLFD (&pfds [i], -1, 0);
414 if (THREAD_WANTS_A_BREAK (thread))
415 mono_thread_interruption_checkpoint ();
418 nsock = mono_poll (pfds, maxfd, -1);
419 } while (nsock == -1 && errno == EINTR);
422 * Apart from EINTR, we only check EBADF, for the rest:
423 * EINVAL: mono_poll() 'protects' us from descriptor
424 * numbers above the limit if using select() by marking
425 * then as MONO_POLLERR. If a system poll() is being
426 * used, the number of descriptor we're passing will not
427 * be over sysconf(_SC_OPEN_MAX), as the error would have
428 * happened when opening.
430 * EFAULT: we own the memory pointed by pfds.
431 * ENOMEM: we're doomed anyway
435 if (nsock == -1 && errno == EBADF) {
436 pfds->revents = 0; /* Just in case... */
437 nsock = mark_bad_fds (pfds, maxfd);
440 if ((pfds->revents & POLL_ERRORS) != 0) {
441 /* We're supposed to die now, as the pipe has been closed */
443 socket_io_cleanup (data);
447 /* Got a new socket */
448 if ((pfds->revents & MONO_POLLIN) != 0) {
451 for (i = 1; i < allocated; i++) {
453 if (pfd->fd == -1 || pfd->fd == data->newpfd->fd)
457 if (i == allocated) {
462 allocated = allocated * 2;
463 pfds = g_renew (mono_pollfd, oldfd, allocated);
465 for (; i < allocated; i++)
466 INIT_POLLFD (&pfds [i], -1, 0);
468 #ifndef PLATFORM_WIN32
469 nread = read (data->pipe [0], one, 1);
471 nread = recv ((SOCKET) data->pipe [0], one, 1, 0);
475 return; /* we're closed */
478 INIT_POLLFD (&pfds [i], data->newpfd->fd, data->newpfd->events);
479 ReleaseSemaphore (data->new_sem, 1, NULL);
488 EnterCriticalSection (&data->io_lock);
489 if (data->inited == 0) {
491 LeaveCriticalSection (&data->io_lock);
492 return; /* cleanup called */
495 for (i = 1; i < maxfd && nsock > 0; i++) {
497 if (pfd->fd == -1 || pfd->revents == 0)
501 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
502 if (list != NULL && (pfd->revents & (MONO_POLLIN | POLL_ERRORS)) != 0) {
503 list = process_io_event (list, MONO_POLLIN);
506 if (list != NULL && (pfd->revents & (MONO_POLLOUT | POLL_ERRORS)) != 0) {
507 list = process_io_event (list, MONO_POLLOUT);
511 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (pfd->fd), list);
512 pfd->events = get_events_from_list (list);
514 mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
520 LeaveCriticalSection (&data->io_lock);
525 #define EPOLL_ERRORS (EPOLLERR | EPOLLHUP)
527 socket_io_epoll_main (gpointer p)
532 struct epoll_event *events, *evt;
533 const int nevents = 512;
537 epollfd = data->epollfd;
538 thread = mono_thread_current ();
539 thread->threadpool_thread = TRUE;
540 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
541 events = g_new0 (struct epoll_event, nevents);
546 if (THREAD_WANTS_A_BREAK (thread))
547 mono_thread_interruption_checkpoint ();
550 g_print ("epoll_wait init\n");
552 ready = epoll_wait (epollfd, events, nevents, -1);
556 g_print ("epoll_wait end with %d ready sockets (%d %s).\n", ready, err, (err) ? g_strerror (err) : "");
560 } while (ready == -1 && errno == EINTR);
566 g_warning ("epoll_wait: %d %s\n", err, g_strerror (err));
572 EnterCriticalSection (&data->io_lock);
573 if (data->inited == 0) {
575 g_print ("data->inited == 0\n");
579 return; /* cleanup called */
582 for (i = 0; i < ready; i++) {
588 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
590 g_print ("Event %d on %d list length: %d\n", evt->events, fd, mono_mlist_length (list));
592 if (list != NULL && (evt->events & (EPOLLIN | EPOLL_ERRORS)) != 0) {
593 list = process_io_event (list, MONO_POLLIN);
596 if (list != NULL && (evt->events & (EPOLLOUT | EPOLL_ERRORS)) != 0) {
597 list = process_io_event (list, MONO_POLLOUT);
601 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (fd), list);
602 evt->events = get_events_from_list (list);
604 g_print ("MOD %d to %d\n", fd, evt->events);
606 if (epoll_ctl (epollfd, EPOLL_CTL_MOD, fd, evt)) {
607 if (epoll_ctl (epollfd, EPOLL_CTL_ADD, fd, evt) == -1) {
610 g_message ("epoll_ctl(MOD): %d %s fd: %d events: %d", err, g_strerror (err), fd, evt->events);
616 mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (fd));
618 g_print ("DEL %d\n", fd);
620 epoll_ctl (epollfd, EPOLL_CTL_DEL, fd, evt);
623 LeaveCriticalSection (&data->io_lock);
629 * select/poll wake up when a socket is closed, but epoll just removes
630 * the socket from its internal list without notification.
633 mono_thread_pool_remove_socket (int sock)
636 MonoMList *list, *next;
637 MonoSocketAsyncResult *state;
639 if (socket_io_data.epoll_disabled == TRUE || socket_io_data.inited == FALSE)
642 EnterCriticalSection (&socket_io_data.io_lock);
643 list = mono_g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
645 mono_g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
647 LeaveCriticalSection (&socket_io_data.io_lock);
650 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
651 if (state->operation == AIO_OP_RECEIVE)
652 state->operation = AIO_OP_RECV_JUST_CALLBACK;
653 else if (state->operation == AIO_OP_SEND)
654 state->operation = AIO_OP_SEND_JUST_CALLBACK;
656 next = mono_mlist_remove_item (list, list);
657 list = process_io_event (list, MONO_POLLIN);
659 process_io_event (list, MONO_POLLOUT);
666 #ifdef PLATFORM_WIN32
668 connect_hack (gpointer x)
670 struct sockaddr_in *addr = (struct sockaddr_in *) x;
673 while (connect ((SOCKET) socket_io_data.pipe [1], (SOCKADDR *) addr, sizeof (struct sockaddr_in))) {
676 g_warning ("Error initializing async. sockets %d.\n", WSAGetLastError ());
677 g_assert (WSAGetLastError ());
684 socket_io_init (SocketIOData *data)
686 #ifdef PLATFORM_WIN32
687 struct sockaddr_in server;
688 struct sockaddr_in client;
694 inited = InterlockedCompareExchange (&data->inited, -1, -1);
698 EnterCriticalSection (&data->io_lock);
699 inited = InterlockedCompareExchange (&data->inited, -1, -1);
701 LeaveCriticalSection (&data->io_lock);
706 data->epoll_disabled = (g_getenv ("MONO_DISABLE_AIO") != NULL);
707 if (FALSE == data->epoll_disabled) {
708 data->epollfd = epoll_create (256);
709 data->epoll_disabled = (data->epollfd == -1);
710 if (data->epoll_disabled && g_getenv ("MONO_DEBUG"))
711 g_message ("epoll_create() failed. Using plain poll().");
716 data->epoll_disabled = TRUE;
719 #ifndef PLATFORM_WIN32
720 if (data->epoll_disabled) {
721 if (pipe (data->pipe) != 0) {
731 srv = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
732 g_assert (srv != INVALID_SOCKET);
733 data->pipe [1] = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
734 g_assert (data->pipe [1] != INVALID_SOCKET);
736 server.sin_family = AF_INET;
737 server.sin_addr.s_addr = inet_addr ("127.0.0.1");
739 if (bind (srv, (SOCKADDR *) &server, sizeof (server))) {
740 g_print ("%d\n", WSAGetLastError ());
744 len = sizeof (server);
745 getsockname (srv, (SOCKADDR *) &server, &len);
747 mono_thread_create (mono_get_root_domain (), connect_hack, &server);
748 len = sizeof (server);
749 data->pipe [0] = accept (srv, (SOCKADDR *) &client, &len);
750 g_assert (data->pipe [0] != INVALID_SOCKET);
753 mono_io_max_worker_threads = mono_max_worker_threads / 2;
754 if (mono_io_max_worker_threads < 10)
755 mono_io_max_worker_threads = 10;
757 data->sock_to_state = mono_g_hash_table_new_type (g_direct_hash, g_direct_equal, MONO_HASH_VALUE_GC);
759 if (data->epoll_disabled) {
760 data->new_sem = CreateSemaphore (NULL, 1, 1, NULL);
761 g_assert (data->new_sem != NULL);
763 io_job_added = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
764 g_assert (io_job_added != NULL);
765 InitializeCriticalSection (&io_queue_lock);
766 if (data->epoll_disabled) {
767 mono_thread_create_internal (mono_get_root_domain (), socket_io_poll_main, data, TRUE);
771 mono_thread_create_internal (mono_get_root_domain (), socket_io_epoll_main, data, TRUE);
774 InterlockedCompareExchange (&data->inited, 1, 0);
775 LeaveCriticalSection (&data->io_lock);
779 socket_io_add_poll (MonoSocketAsyncResult *state)
784 SocketIOData *data = &socket_io_data;
786 #if defined(PLATFORM_MACOSX) || defined(PLATFORM_BSD6) || defined(PLATFORM_WIN32) || defined(PLATFORM_SOLARIS)
787 /* select() for connect() does not work well on the Mac. Bug #75436. */
788 /* Bug #77637 for the BSD 6 case */
789 /* Bug #78888 for the Windows case */
790 if (state->operation == AIO_OP_CONNECT && state->blocking == TRUE) {
791 start_io_thread_or_queue (state);
795 WaitForSingleObject (data->new_sem, INFINITE);
796 if (data->newpfd == NULL)
797 data->newpfd = g_new0 (mono_pollfd, 1);
799 EnterCriticalSection (&data->io_lock);
800 /* FIXME: 64 bit issue: handle can be a pointer on windows? */
801 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (state->handle));
803 list = mono_mlist_alloc ((MonoObject*)state);
805 list = mono_mlist_append (list, (MonoObject*)state);
808 events = get_events_from_list (list);
809 INIT_POLLFD (data->newpfd, GPOINTER_TO_INT (state->handle), events);
810 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (state->handle), list);
811 LeaveCriticalSection (&data->io_lock);
812 *msg = (char) state->operation;
813 #ifndef PLATFORM_WIN32
814 write (data->pipe [1], msg, 1);
816 send ((SOCKET) data->pipe [1], msg, 1, 0);
822 socket_io_add_epoll (MonoSocketAsyncResult *state)
825 SocketIOData *data = &socket_io_data;
826 struct epoll_event event;
830 memset (&event, 0, sizeof (struct epoll_event));
831 fd = GPOINTER_TO_INT (state->handle);
832 EnterCriticalSection (&data->io_lock);
833 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
835 list = mono_mlist_alloc ((MonoObject*)state);
836 epoll_op = EPOLL_CTL_ADD;
838 list = mono_mlist_append (list, (MonoObject*)state);
839 epoll_op = EPOLL_CTL_MOD;
842 ievt = get_events_from_list (list);
843 if ((ievt & MONO_POLLIN) != 0)
844 event.events |= EPOLLIN;
845 if ((ievt & MONO_POLLOUT) != 0)
846 event.events |= EPOLLOUT;
848 mono_g_hash_table_replace (data->sock_to_state, state->handle, list);
851 g_print ("%s %d with %d\n", epoll_op == EPOLL_CTL_ADD ? "ADD" : "MOD", fd, event.events);
853 if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
855 if (epoll_op == EPOLL_CTL_ADD && err == EEXIST) {
856 epoll_op = EPOLL_CTL_MOD;
857 if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
858 g_message ("epoll_ctl(MOD): %d %s\n", err, g_strerror (err));
863 LeaveCriticalSection (&data->io_lock);
869 socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
871 socket_io_init (&socket_io_data);
872 MONO_OBJECT_SETREF (state, ares, ares);
874 if (socket_io_data.epoll_disabled == FALSE) {
875 if (socket_io_add_epoll (state))
879 socket_io_add_poll (state);
883 socket_io_filter (MonoObject *target, MonoObject *state)
886 MonoSocketAsyncResult *sock_res = (MonoSocketAsyncResult *) state;
889 if (target == NULL || state == NULL)
892 if (socket_async_call_klass == NULL) {
893 klass = target->vtable->klass;
894 /* Check if it's SocketAsyncCall in System.Net.Sockets
895 * FIXME: check the assembly is signed correctly for extra care
897 if (klass->name [0] == 'S' && strcmp (klass->name, "SocketAsyncCall") == 0
898 && strcmp (mono_image_get_name (klass->image), "System") == 0
899 && klass->nested_in && strcmp (klass->nested_in->name, "Socket") == 0)
900 socket_async_call_klass = klass;
903 if (process_async_call_klass == NULL) {
904 klass = target->vtable->klass;
905 /* Check if it's AsyncReadHandler in System.Diagnostics.Process
906 * FIXME: check the assembly is signed correctly for extra care
908 if (klass->name [0] == 'A' && strcmp (klass->name, "AsyncReadHandler") == 0
909 && strcmp (mono_image_get_name (klass->image), "System") == 0
910 && klass->nested_in && strcmp (klass->nested_in->name, "Process") == 0)
911 process_async_call_klass = klass;
913 /* return both when socket_async_call_klass has not been seen yet and when
914 * the object is not an instance of the class.
916 if (target->vtable->klass != socket_async_call_klass && target->vtable->klass != process_async_call_klass)
919 op = sock_res->operation;
920 if (op < AIO_OP_FIRST || op >= AIO_OP_LAST)
927 mono_async_invoke (MonoAsyncResult *ares)
929 ASyncCall *ac = (ASyncCall *)ares->object_data;
930 MonoThread *thread = NULL;
931 MonoObject *res, *exc = NULL;
932 MonoArray *out_args = NULL;
934 if (ares->execution_context) {
935 /* use captured ExecutionContext (if available) */
936 thread = mono_thread_current ();
937 MONO_OBJECT_SETREF (ares, original_context, thread->execution_context);
938 MONO_OBJECT_SETREF (thread, execution_context, ares->execution_context);
940 ares->original_context = NULL;
944 res = mono_message_invoke (ares->async_delegate, ac->msg, &exc, &out_args);
945 MONO_OBJECT_SETREF (ac, res, res);
946 MONO_OBJECT_SETREF (ac, msg->exc, exc);
947 MONO_OBJECT_SETREF (ac, out_args, out_args);
951 /* call async callback if cb_method != null*/
953 MonoObject *exc = NULL;
955 mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &exc);
956 /* 'exc' will be the previous ac->msg->exc if not NULL and not
957 * catched. If catched, this will be set to NULL and the
958 * exception will not be printed. */
959 MONO_OBJECT_SETREF (ac->msg, exc, exc);
962 /* restore original thread execution context if flow isn't suppressed, i.e. non null */
963 if (ares->original_context) {
964 MONO_OBJECT_SETREF (thread, execution_context, ares->original_context);
965 ares->original_context = NULL;
968 /* notify listeners */
969 mono_monitor_enter ((MonoObject *) ares);
970 if (ares->handle != NULL) {
971 ac->wait_event = (gsize) mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
972 SetEvent ((gpointer)(gsize)ac->wait_event);
974 mono_monitor_exit ((MonoObject *) ares);
976 EnterCriticalSection (&ares_lock);
977 mono_g_hash_table_remove (ares_htable, ares);
978 LeaveCriticalSection (&ares_lock);
982 mono_thread_pool_init ()
985 int threads_per_cpu = THREADS_PER_CPU;
987 if ((int) InterlockedCompareExchange (&tp_inited, 1, 0) == 1)
990 MONO_GC_REGISTER_ROOT (ares_htable);
991 MONO_GC_REGISTER_ROOT (socket_io_data.sock_to_state);
992 InitializeCriticalSection (&socket_io_data.io_lock);
993 InitializeCriticalSection (&ares_lock);
994 ares_htable = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_VALUE_GC);
995 job_added = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
996 g_assert (job_added != NULL);
997 GetSystemInfo (&info);
998 if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
999 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
1000 if (threads_per_cpu <= 0)
1001 threads_per_cpu = THREADS_PER_CPU;
1004 mono_max_worker_threads = 20 + threads_per_cpu * info.dwNumberOfProcessors;
1006 async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
1007 g_assert (async_call_klass);
1011 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
1014 MonoDomain *domain = mono_domain_get ();
1015 MonoAsyncResult *ares;
1018 ac = (ASyncCall*)mono_object_new (mono_domain_get (), async_call_klass);
1019 MONO_OBJECT_SETREF (ac, msg, msg);
1020 MONO_OBJECT_SETREF (ac, state, state);
1022 if (async_callback) {
1023 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
1024 MONO_OBJECT_SETREF (ac, cb_target, async_callback);
1027 ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
1028 MONO_OBJECT_SETREF (ares, async_delegate, target);
1030 EnterCriticalSection (&ares_lock);
1031 mono_g_hash_table_insert (ares_htable, ares, ares);
1032 LeaveCriticalSection (&ares_lock);
1034 if (socket_io_filter (target, state)) {
1035 socket_io_add (ares, (MonoSocketAsyncResult *) state);
1039 start_thread_or_queue (ares);
1044 start_thread_or_queue (MonoAsyncResult *ares)
1048 busy = (int) InterlockedCompareExchange (&busy_worker_threads, 0, -1);
1049 worker = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1050 if (worker <= ++busy &&
1051 worker < mono_max_worker_threads) {
1052 InterlockedIncrement (&mono_worker_threads);
1053 InterlockedIncrement (&busy_worker_threads);
1054 mono_thread_create_internal (mono_get_root_domain (), async_invoke_thread, ares, TRUE);
1056 append_job (&mono_delegate_section, &async_call_queue, (MonoObject*)ares);
1057 ReleaseSemaphore (job_added, 1, NULL);
1062 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1069 /* check if already finished */
1070 mono_monitor_enter ((MonoObject *) ares);
1072 if (ares->endinvoke_called) {
1073 *exc = (MonoObject *)mono_exception_from_name (mono_defaults.corlib, "System",
1074 "InvalidOperationException");
1075 mono_monitor_exit ((MonoObject *) ares);
1079 ares->endinvoke_called = 1;
1080 ac = (ASyncCall *)ares->object_data;
1082 g_assert (ac != NULL);
1084 /* wait until we are really finished */
1085 if (!ares->completed) {
1086 if (ares->handle == NULL) {
1087 ac->wait_event = (gsize)CreateEvent (NULL, TRUE, FALSE, NULL);
1088 g_assert(ac->wait_event != 0);
1089 MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), (gpointer)(gsize)ac->wait_event));
1091 mono_monitor_exit ((MonoObject *) ares);
1092 WaitForSingleObjectEx ((gpointer)(gsize)ac->wait_event, INFINITE, TRUE);
1094 mono_monitor_exit ((MonoObject *) ares);
1097 *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1098 *out_args = ac->out_args;
1104 mono_thread_pool_cleanup (void)
1108 EnterCriticalSection (&mono_delegate_section);
1109 free_queue (&async_call_queue);
1110 release = (gint) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1111 LeaveCriticalSection (&mono_delegate_section);
1113 ReleaseSemaphore (job_added, release, NULL);
1115 socket_io_cleanup (&socket_io_data);
1119 append_job (CRITICAL_SECTION *cs, TPQueue *list, MonoObject *ar)
1121 EnterCriticalSection (cs);
1122 if (list->array && (list->next_elem < mono_array_length (list->array))) {
1123 mono_array_setref (list->array, list->next_elem, ar);
1125 LeaveCriticalSection (cs);
1129 MONO_GC_REGISTER_ROOT (list->array);
1130 list->array = mono_array_new (mono_get_root_domain (), mono_defaults.object_class, 16);
1132 int count = list->next_elem - list->first_elem;
1133 /* slide the array or create a larger one if it's full */
1134 if (list->first_elem) {
1135 mono_array_memcpy_refs (list->array, 0, list->array, list->first_elem, count);
1137 MonoArray *newa = mono_array_new (mono_get_root_domain (), mono_defaults.object_class, mono_array_length (list->array) * 2);
1138 mono_array_memcpy_refs (newa, 0, list->array, list->first_elem, count);
1141 list->first_elem = 0;
1142 list->next_elem = count;
1144 mono_array_setref (list->array, list->next_elem, ar);
1146 LeaveCriticalSection (cs);
1150 dequeue_job (CRITICAL_SECTION *cs, TPQueue *list)
1155 EnterCriticalSection (cs);
1156 if (!list->array || list->first_elem == list->next_elem) {
1157 LeaveCriticalSection (cs);
1160 ar = mono_array_get (list->array, MonoObject*, list->first_elem);
1162 count = list->next_elem - list->first_elem;
1163 /* reduce the size of the array if it's mostly empty */
1164 if (mono_array_length (list->array) > 16 && count < (mono_array_length (list->array) / 3)) {
1165 MonoArray *newa = mono_array_new (mono_get_root_domain (), mono_defaults.object_class, mono_array_length (list->array) / 2);
1166 mono_array_memcpy_refs (newa, 0, list->array, list->first_elem, count);
1168 list->first_elem = 0;
1169 list->next_elem = count;
1171 LeaveCriticalSection (cs);
1177 free_queue (TPQueue *list)
1180 list->first_elem = list->next_elem = 0;
1184 async_invoke_thread (gpointer data)
1190 thread = mono_thread_current ();
1191 thread->threadpool_thread = TRUE;
1192 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
1195 MonoAsyncResult *ar;
1197 ar = (MonoAsyncResult *) data;
1199 /* worker threads invokes methods in different domains,
1200 * so we need to set the right domain here */
1201 domain = ((MonoObject *)ar)->vtable->domain;
1202 mono_thread_push_appdomain_ref (domain);
1203 if (mono_domain_set (domain, FALSE)) {
1206 mono_async_invoke (ar);
1207 ac = (ASyncCall *) ar->object_data;
1209 if (ac->msg->exc != NULL)
1210 mono_unhandled_exception (ac->msg->exc);
1212 mono_domain_set (mono_get_root_domain (), TRUE);
1214 mono_thread_pop_appdomain_ref ();
1215 InterlockedDecrement (&busy_worker_threads);
1218 data = dequeue_job (&mono_delegate_section, &async_call_queue);
1222 int timeout = 10000;
1223 guint32 start_time = GetTickCount ();
1226 wr = WaitForSingleObjectEx (job_added, (guint32)timeout, TRUE);
1227 if (THREAD_WANTS_A_BREAK (thread))
1228 mono_thread_interruption_checkpoint ();
1230 timeout -= GetTickCount () - start_time;
1232 if (wr != WAIT_TIMEOUT)
1233 data = dequeue_job (&mono_delegate_section, &async_call_queue);
1235 while (!data && timeout > 0);
1239 workers = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1240 min = (int) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
1242 while (!data && workers <= min) {
1243 WaitForSingleObjectEx (job_added, INFINITE, TRUE);
1244 if (THREAD_WANTS_A_BREAK (thread))
1245 mono_thread_interruption_checkpoint ();
1247 data = dequeue_job (&mono_delegate_section, &async_call_queue);
1248 workers = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1249 min = (int) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
1254 InterlockedDecrement (&mono_worker_threads);
1258 InterlockedIncrement (&busy_worker_threads);
1261 g_assert_not_reached ();
1265 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
1269 MONO_ARCH_SAVE_REGS;
1271 busy = (gint) InterlockedCompareExchange (&busy_worker_threads, 0, -1);
1272 busy_io = (gint) InterlockedCompareExchange (&busy_io_worker_threads, 0, -1);
1273 *workerThreads = mono_max_worker_threads - busy;
1274 *completionPortThreads = mono_io_max_worker_threads - busy_io;
1278 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
1280 MONO_ARCH_SAVE_REGS;
1282 *workerThreads = mono_max_worker_threads;
1283 *completionPortThreads = mono_io_max_worker_threads;
1287 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
1289 gint workers, workers_io;
1291 MONO_ARCH_SAVE_REGS;
1293 workers = (gint) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
1294 workers_io = (gint) InterlockedCompareExchange (&mono_io_min_worker_threads, 0, -1);
1296 *workerThreads = workers;
1297 *completionPortThreads = workers_io;
1301 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
1303 MONO_ARCH_SAVE_REGS;
1305 if (workerThreads < 0 || workerThreads > mono_max_worker_threads)
1308 if (completionPortThreads < 0 || completionPortThreads > mono_io_max_worker_threads)
1311 InterlockedExchange (&mono_min_worker_threads, workerThreads);
1312 InterlockedExchange (&mono_io_min_worker_threads, completionPortThreads);
1313 /* FIXME: should actually start the idle threads if needed */
1318 ves_icall_System_Threading_ThreadPool_SetMaxThreads (gint workerThreads, gint completionPortThreads)
1320 MONO_ARCH_SAVE_REGS;
1322 if (workerThreads < mono_max_worker_threads)
1325 if (completionPortThreads < mono_io_max_worker_threads)
1328 InterlockedExchange (&mono_max_worker_threads, workerThreads);
1329 InterlockedExchange (&mono_io_max_worker_threads, completionPortThreads);