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/metadata/gc-internal.h>
35 #include <mono/utils/mono-time.h>
37 #ifdef HAVE_SYS_TIME_H
40 #include <sys/types.h>
47 #include <mono/utils/mono-poll.h>
49 #include <sys/epoll.h>
52 #include "mono/io-layer/socket-wrappers.h"
54 #include "threadpool.h"
56 #define THREAD_WANTS_A_BREAK(t) ((t->state & (ThreadState_StopRequested | \
57 ThreadState_SuspendRequested)) != 0)
61 /* maximum number of worker threads */
62 static int mono_max_worker_threads;
63 static int mono_min_worker_threads;
64 static int mono_io_max_worker_threads;
65 static int mono_io_min_worker_threads;
67 /* current number of worker threads */
68 static int mono_worker_threads = 0;
69 static int io_worker_threads = 0;
71 /* current number of busy threads */
72 static int busy_worker_threads = 0;
73 static int busy_io_worker_threads;
75 /* mono_thread_pool_init called */
78 /* we use this to store a reference to the AsyncResult to avoid GC */
79 static MonoGHashTable *ares_htable = NULL;
81 static CRITICAL_SECTION ares_lock;
82 static CRITICAL_SECTION io_queue_lock;
83 static int pending_io_items;
86 CRITICAL_SECTION io_lock; /* access to sock_to_state */
89 MonoGHashTable *sock_to_state;
91 HANDLE new_sem; /* access to newpfd and write side of the pipe */
93 gboolean epoll_disabled;
99 static SocketIOData socket_io_data;
101 /* we append a job */
102 static HANDLE job_added;
103 static HANDLE io_job_added;
105 /* Keep in sync with the System.MonoAsyncCall class which provides GC tracking */
108 MonoMethodMessage *msg;
109 MonoMethod *cb_method;
110 MonoDelegate *cb_target;
114 /* This is a HANDLE, we use guint64 so the managed object layout remains constant */
124 static void async_invoke_thread (gpointer data);
125 static void append_job (CRITICAL_SECTION *cs, TPQueue *list, MonoObject *ar);
126 static void start_thread_or_queue (MonoAsyncResult *ares);
127 static void mono_async_invoke (MonoAsyncResult *ares);
128 static MonoObject* dequeue_job (CRITICAL_SECTION *cs, TPQueue *list);
129 static void free_queue (TPQueue *list);
131 static TPQueue async_call_queue = {NULL, 0, 0};
132 static TPQueue async_io_queue = {NULL, 0, 0};
134 static MonoClass *async_call_klass;
135 static MonoClass *socket_async_call_klass;
136 static MonoClass *process_async_call_klass;
138 #define INIT_POLLFD(a, b, c) {(a)->fd = b; (a)->events = c; (a)->revents = 0;}
147 AIO_OP_RECV_JUST_CALLBACK,
148 AIO_OP_SEND_JUST_CALLBACK,
154 socket_io_cleanup (SocketIOData *data)
158 if (data->inited == 0)
161 EnterCriticalSection (&data->io_lock);
163 #ifdef PLATFORM_WIN32
164 closesocket (data->pipe [0]);
165 closesocket (data->pipe [1]);
167 close (data->pipe [0]);
168 close (data->pipe [1]);
173 CloseHandle (data->new_sem);
174 data->new_sem = NULL;
175 mono_g_hash_table_destroy (data->sock_to_state);
176 data->sock_to_state = NULL;
177 free_queue (&async_io_queue);
178 release = (gint) InterlockedCompareExchange (&io_worker_threads, 0, -1);
180 ReleaseSemaphore (io_job_added, release, NULL);
181 g_free (data->newpfd);
184 if (FALSE == data->epoll_disabled)
185 close (data->epollfd);
187 LeaveCriticalSection (&data->io_lock);
191 get_event_from_state (MonoSocketAsyncResult *state)
193 switch (state->operation) {
196 case AIO_OP_RECV_JUST_CALLBACK:
197 case AIO_OP_RECEIVEFROM:
198 case AIO_OP_READPIPE:
201 case AIO_OP_SEND_JUST_CALLBACK:
205 default: /* Should never happen */
206 g_print ("get_event_from_state: unknown value in switch!!!\n");
212 get_events_from_list (MonoMList *list)
214 MonoSocketAsyncResult *state;
217 while (list && (state = (MonoSocketAsyncResult *)mono_mlist_get_data (list))) {
218 events |= get_event_from_state (state);
219 list = mono_mlist_next (list);
225 #define ICALL_RECV(x) ves_icall_System_Net_Sockets_Socket_Receive_internal (\
226 (SOCKET) x->handle, x->buffer, x->offset, x->size,\
227 x->socket_flags, &x->error);
229 #define ICALL_SEND(x) ves_icall_System_Net_Sockets_Socket_Send_internal (\
230 (SOCKET) x->handle, x->buffer, x->offset, x->size,\
231 x->socket_flags, &x->error);
234 async_invoke_io_thread (gpointer data)
238 thread = mono_thread_current ();
239 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
242 MonoSocketAsyncResult *state;
245 state = (MonoSocketAsyncResult *) data;
247 InterlockedDecrement (&pending_io_items);
249 switch (state->operation) {
251 state->total = ICALL_RECV (state);
254 state->total = ICALL_SEND (state);
258 /* worker threads invokes methods in different domains,
259 * so we need to set the right domain here */
260 domain = ((MonoObject *)ar)->vtable->domain;
261 mono_thread_push_appdomain_ref (domain);
262 if (mono_domain_set (domain, FALSE)) {
265 mono_async_invoke (ar);
266 ac = (ASyncCall *) ar->object_data;
268 if (ac->msg->exc != NULL)
269 mono_unhandled_exception (ac->msg->exc);
271 mono_domain_set (mono_get_root_domain (), TRUE);
273 mono_thread_pop_appdomain_ref ();
274 InterlockedDecrement (&busy_io_worker_threads);
277 data = dequeue_job (&io_queue_lock, &async_io_queue);
282 guint32 start_time = mono_msec_ticks ();
285 wr = WaitForSingleObjectEx (io_job_added, (guint32)timeout, TRUE);
286 if (THREAD_WANTS_A_BREAK (thread))
287 mono_thread_interruption_checkpoint ();
289 timeout -= mono_msec_ticks () - start_time;
291 if (wr != WAIT_TIMEOUT)
292 data = dequeue_job (&io_queue_lock, &async_io_queue);
294 while (!data && timeout > 0);
298 if (InterlockedDecrement (&io_worker_threads) < 2) {
299 /* If we have pending items, keep the thread alive */
300 if (InterlockedCompareExchange (&pending_io_items, 0, 0) != 0) {
301 InterlockedIncrement (&io_worker_threads);
308 InterlockedIncrement (&busy_io_worker_threads);
311 g_assert_not_reached ();
315 start_io_thread_or_queue (MonoSocketAsyncResult *ares)
320 busy = (int) InterlockedCompareExchange (&busy_io_worker_threads, 0, -1);
321 worker = (int) InterlockedCompareExchange (&io_worker_threads, 0, -1);
322 if (worker <= ++busy &&
323 worker < mono_io_max_worker_threads) {
324 InterlockedIncrement (&busy_io_worker_threads);
325 InterlockedIncrement (&io_worker_threads);
326 domain = ((ares) ? ((MonoObject *) ares)->vtable->domain : mono_domain_get ());
327 mono_thread_create_internal (mono_get_root_domain (), async_invoke_io_thread, ares, TRUE);
329 append_job (&io_queue_lock, &async_io_queue, (MonoObject*)ares);
330 ReleaseSemaphore (io_job_added, 1, NULL);
335 process_io_event (MonoMList *list, int event)
337 MonoSocketAsyncResult *state;
343 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
344 if (get_event_from_state (state) == event)
347 list = mono_mlist_next (list);
351 oldlist = mono_mlist_remove_item (oldlist, list);
353 g_print ("Dispatching event %d on socket %d\n", event, state->handle);
355 InterlockedIncrement (&pending_io_items);
356 start_io_thread_or_queue (state);
363 mark_bad_fds (mono_pollfd *pfds, int nfds)
369 for (i = 0; i < nfds; i++) {
374 ret = mono_poll (pfd, 1, 0);
375 if (ret == -1 && errno == EBADF) {
376 pfd->revents |= MONO_POLLNVAL;
378 } else if (ret == 1) {
387 socket_io_poll_main (gpointer p)
389 #define INITIAL_POLLFD_SIZE 1024
390 #define POLL_ERRORS (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL)
391 SocketIOData *data = p;
398 thread = mono_thread_current ();
399 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
401 allocated = INITIAL_POLLFD_SIZE;
402 pfds = g_new0 (mono_pollfd, allocated);
403 INIT_POLLFD (pfds, data->pipe [0], MONO_POLLIN);
404 for (i = 1; i < allocated; i++)
405 INIT_POLLFD (&pfds [i], -1, 0);
415 if (THREAD_WANTS_A_BREAK (thread))
416 mono_thread_interruption_checkpoint ();
419 nsock = mono_poll (pfds, maxfd, -1);
420 } while (nsock == -1 && errno == EINTR);
423 * Apart from EINTR, we only check EBADF, for the rest:
424 * EINVAL: mono_poll() 'protects' us from descriptor
425 * numbers above the limit if using select() by marking
426 * then as MONO_POLLERR. If a system poll() is being
427 * used, the number of descriptor we're passing will not
428 * be over sysconf(_SC_OPEN_MAX), as the error would have
429 * happened when opening.
431 * EFAULT: we own the memory pointed by pfds.
432 * ENOMEM: we're doomed anyway
436 if (nsock == -1 && errno == EBADF) {
437 pfds->revents = 0; /* Just in case... */
438 nsock = mark_bad_fds (pfds, maxfd);
441 if ((pfds->revents & POLL_ERRORS) != 0) {
442 /* We're supposed to die now, as the pipe has been closed */
444 socket_io_cleanup (data);
448 /* Got a new socket */
449 if ((pfds->revents & MONO_POLLIN) != 0) {
452 for (i = 1; i < allocated; i++) {
454 if (pfd->fd == -1 || pfd->fd == data->newpfd->fd)
458 if (i == allocated) {
463 allocated = allocated * 2;
464 pfds = g_renew (mono_pollfd, oldfd, allocated);
466 for (; i < allocated; i++)
467 INIT_POLLFD (&pfds [i], -1, 0);
469 #ifndef PLATFORM_WIN32
470 nread = read (data->pipe [0], one, 1);
472 nread = recv ((SOCKET) data->pipe [0], one, 1, 0);
476 return; /* we're closed */
479 INIT_POLLFD (&pfds [i], data->newpfd->fd, data->newpfd->events);
480 ReleaseSemaphore (data->new_sem, 1, NULL);
489 EnterCriticalSection (&data->io_lock);
490 if (data->inited == 0) {
492 LeaveCriticalSection (&data->io_lock);
493 return; /* cleanup called */
496 for (i = 1; i < maxfd && nsock > 0; i++) {
498 if (pfd->fd == -1 || pfd->revents == 0)
502 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
503 if (list != NULL && (pfd->revents & (MONO_POLLIN | POLL_ERRORS)) != 0) {
504 list = process_io_event (list, MONO_POLLIN);
507 if (list != NULL && (pfd->revents & (MONO_POLLOUT | POLL_ERRORS)) != 0) {
508 list = process_io_event (list, MONO_POLLOUT);
512 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (pfd->fd), list);
513 pfd->events = get_events_from_list (list);
515 mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
521 LeaveCriticalSection (&data->io_lock);
526 #define EPOLL_ERRORS (EPOLLERR | EPOLLHUP)
528 socket_io_epoll_main (gpointer p)
533 struct epoll_event *events, *evt;
534 const int nevents = 512;
538 epollfd = data->epollfd;
539 thread = mono_thread_current ();
540 thread->threadpool_thread = TRUE;
541 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
542 events = g_new0 (struct epoll_event, nevents);
547 if (THREAD_WANTS_A_BREAK (thread))
548 mono_thread_interruption_checkpoint ();
551 g_print ("epoll_wait init\n");
553 ready = epoll_wait (epollfd, events, nevents, -1);
557 g_print ("epoll_wait end with %d ready sockets (%d %s).\n", ready, err, (err) ? g_strerror (err) : "");
561 } while (ready == -1 && errno == EINTR);
567 g_warning ("epoll_wait: %d %s\n", err, g_strerror (err));
573 EnterCriticalSection (&data->io_lock);
574 if (data->inited == 0) {
576 g_print ("data->inited == 0\n");
580 return; /* cleanup called */
583 for (i = 0; i < ready; i++) {
589 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
591 g_print ("Event %d on %d list length: %d\n", evt->events, fd, mono_mlist_length (list));
593 if (list != NULL && (evt->events & (EPOLLIN | EPOLL_ERRORS)) != 0) {
594 list = process_io_event (list, MONO_POLLIN);
597 if (list != NULL && (evt->events & (EPOLLOUT | EPOLL_ERRORS)) != 0) {
598 list = process_io_event (list, MONO_POLLOUT);
602 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (fd), list);
603 evt->events = get_events_from_list (list);
605 g_print ("MOD %d to %d\n", fd, evt->events);
607 if (epoll_ctl (epollfd, EPOLL_CTL_MOD, fd, evt)) {
608 if (epoll_ctl (epollfd, EPOLL_CTL_ADD, fd, evt) == -1) {
611 g_message ("epoll_ctl(MOD): %d %s fd: %d events: %d", err, g_strerror (err), fd, evt->events);
617 mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (fd));
619 g_print ("DEL %d\n", fd);
621 epoll_ctl (epollfd, EPOLL_CTL_DEL, fd, evt);
624 LeaveCriticalSection (&data->io_lock);
630 * select/poll wake up when a socket is closed, but epoll just removes
631 * the socket from its internal list without notification.
634 mono_thread_pool_remove_socket (int sock)
637 MonoMList *list, *next;
638 MonoSocketAsyncResult *state;
640 if (socket_io_data.epoll_disabled == TRUE || socket_io_data.inited == FALSE)
643 EnterCriticalSection (&socket_io_data.io_lock);
644 list = mono_g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
646 mono_g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
648 LeaveCriticalSection (&socket_io_data.io_lock);
651 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
652 if (state->operation == AIO_OP_RECEIVE)
653 state->operation = AIO_OP_RECV_JUST_CALLBACK;
654 else if (state->operation == AIO_OP_SEND)
655 state->operation = AIO_OP_SEND_JUST_CALLBACK;
657 next = mono_mlist_remove_item (list, list);
658 list = process_io_event (list, MONO_POLLIN);
660 process_io_event (list, MONO_POLLOUT);
667 #ifdef PLATFORM_WIN32
669 connect_hack (gpointer x)
671 struct sockaddr_in *addr = (struct sockaddr_in *) x;
674 while (connect ((SOCKET) socket_io_data.pipe [1], (SOCKADDR *) addr, sizeof (struct sockaddr_in))) {
677 g_warning ("Error initializing async. sockets %d.\n", WSAGetLastError ());
678 g_assert (WSAGetLastError ());
685 socket_io_init (SocketIOData *data)
687 #ifdef PLATFORM_WIN32
688 struct sockaddr_in server;
689 struct sockaddr_in client;
695 inited = InterlockedCompareExchange (&data->inited, -1, -1);
699 EnterCriticalSection (&data->io_lock);
700 inited = InterlockedCompareExchange (&data->inited, -1, -1);
702 LeaveCriticalSection (&data->io_lock);
707 data->epoll_disabled = (g_getenv ("MONO_DISABLE_AIO") != NULL);
708 if (FALSE == data->epoll_disabled) {
709 data->epollfd = epoll_create (256);
710 data->epoll_disabled = (data->epollfd == -1);
711 if (data->epoll_disabled && g_getenv ("MONO_DEBUG"))
712 g_message ("epoll_create() failed. Using plain poll().");
717 data->epoll_disabled = TRUE;
720 #ifndef PLATFORM_WIN32
721 if (data->epoll_disabled) {
722 if (pipe (data->pipe) != 0) {
732 srv = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
733 g_assert (srv != INVALID_SOCKET);
734 data->pipe [1] = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
735 g_assert (data->pipe [1] != INVALID_SOCKET);
737 server.sin_family = AF_INET;
738 server.sin_addr.s_addr = inet_addr ("127.0.0.1");
740 if (bind (srv, (SOCKADDR *) &server, sizeof (server))) {
741 g_print ("%d\n", WSAGetLastError ());
745 len = sizeof (server);
746 getsockname (srv, (SOCKADDR *) &server, &len);
748 mono_thread_create (mono_get_root_domain (), connect_hack, &server);
749 len = sizeof (server);
750 data->pipe [0] = accept (srv, (SOCKADDR *) &client, &len);
751 g_assert (data->pipe [0] != INVALID_SOCKET);
754 mono_io_max_worker_threads = mono_max_worker_threads / 2;
755 if (mono_io_max_worker_threads < 10)
756 mono_io_max_worker_threads = 10;
758 data->sock_to_state = mono_g_hash_table_new_type (g_direct_hash, g_direct_equal, MONO_HASH_VALUE_GC);
760 if (data->epoll_disabled) {
761 data->new_sem = CreateSemaphore (NULL, 1, 1, NULL);
762 g_assert (data->new_sem != NULL);
764 io_job_added = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
765 g_assert (io_job_added != NULL);
766 InitializeCriticalSection (&io_queue_lock);
767 if (data->epoll_disabled) {
768 mono_thread_create_internal (mono_get_root_domain (), socket_io_poll_main, data, TRUE);
772 mono_thread_create_internal (mono_get_root_domain (), socket_io_epoll_main, data, TRUE);
775 InterlockedCompareExchange (&data->inited, 1, 0);
776 LeaveCriticalSection (&data->io_lock);
780 socket_io_add_poll (MonoSocketAsyncResult *state)
785 SocketIOData *data = &socket_io_data;
787 #if defined(PLATFORM_MACOSX) || defined(PLATFORM_BSD6) || defined(PLATFORM_WIN32) || defined(PLATFORM_SOLARIS)
788 /* select() for connect() does not work well on the Mac. Bug #75436. */
789 /* Bug #77637 for the BSD 6 case */
790 /* Bug #78888 for the Windows case */
791 if (state->operation == AIO_OP_CONNECT && state->blocking == TRUE) {
792 start_io_thread_or_queue (state);
796 WaitForSingleObject (data->new_sem, INFINITE);
797 if (data->newpfd == NULL)
798 data->newpfd = g_new0 (mono_pollfd, 1);
800 EnterCriticalSection (&data->io_lock);
801 /* FIXME: 64 bit issue: handle can be a pointer on windows? */
802 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (state->handle));
804 list = mono_mlist_alloc ((MonoObject*)state);
806 list = mono_mlist_append (list, (MonoObject*)state);
809 events = get_events_from_list (list);
810 INIT_POLLFD (data->newpfd, GPOINTER_TO_INT (state->handle), events);
811 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (state->handle), list);
812 LeaveCriticalSection (&data->io_lock);
813 *msg = (char) state->operation;
814 #ifndef PLATFORM_WIN32
815 write (data->pipe [1], msg, 1);
817 send ((SOCKET) data->pipe [1], msg, 1, 0);
823 socket_io_add_epoll (MonoSocketAsyncResult *state)
826 SocketIOData *data = &socket_io_data;
827 struct epoll_event event;
831 memset (&event, 0, sizeof (struct epoll_event));
832 fd = GPOINTER_TO_INT (state->handle);
833 EnterCriticalSection (&data->io_lock);
834 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
836 list = mono_mlist_alloc ((MonoObject*)state);
837 epoll_op = EPOLL_CTL_ADD;
839 list = mono_mlist_append (list, (MonoObject*)state);
840 epoll_op = EPOLL_CTL_MOD;
843 ievt = get_events_from_list (list);
844 if ((ievt & MONO_POLLIN) != 0)
845 event.events |= EPOLLIN;
846 if ((ievt & MONO_POLLOUT) != 0)
847 event.events |= EPOLLOUT;
849 mono_g_hash_table_replace (data->sock_to_state, state->handle, list);
852 g_print ("%s %d with %d\n", epoll_op == EPOLL_CTL_ADD ? "ADD" : "MOD", fd, event.events);
854 if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
856 if (epoll_op == EPOLL_CTL_ADD && err == EEXIST) {
857 epoll_op = EPOLL_CTL_MOD;
858 if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
859 g_message ("epoll_ctl(MOD): %d %s\n", err, g_strerror (err));
864 LeaveCriticalSection (&data->io_lock);
870 socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
872 socket_io_init (&socket_io_data);
873 MONO_OBJECT_SETREF (state, ares, ares);
875 if (socket_io_data.epoll_disabled == FALSE) {
876 if (socket_io_add_epoll (state))
880 socket_io_add_poll (state);
884 socket_io_filter (MonoObject *target, MonoObject *state)
887 MonoSocketAsyncResult *sock_res = (MonoSocketAsyncResult *) state;
890 if (target == NULL || state == NULL)
893 if (socket_async_call_klass == NULL) {
894 klass = target->vtable->klass;
895 /* Check if it's SocketAsyncCall in System.Net.Sockets
896 * FIXME: check the assembly is signed correctly for extra care
898 if (klass->name [0] == 'S' && strcmp (klass->name, "SocketAsyncCall") == 0
899 && strcmp (mono_image_get_name (klass->image), "System") == 0
900 && klass->nested_in && strcmp (klass->nested_in->name, "Socket") == 0)
901 socket_async_call_klass = klass;
904 if (process_async_call_klass == NULL) {
905 klass = target->vtable->klass;
906 /* Check if it's AsyncReadHandler in System.Diagnostics.Process
907 * FIXME: check the assembly is signed correctly for extra care
909 if (klass->name [0] == 'A' && strcmp (klass->name, "AsyncReadHandler") == 0
910 && strcmp (mono_image_get_name (klass->image), "System") == 0
911 && klass->nested_in && strcmp (klass->nested_in->name, "Process") == 0)
912 process_async_call_klass = klass;
914 /* return both when socket_async_call_klass has not been seen yet and when
915 * the object is not an instance of the class.
917 if (target->vtable->klass != socket_async_call_klass && target->vtable->klass != process_async_call_klass)
920 op = sock_res->operation;
921 if (op < AIO_OP_FIRST || op >= AIO_OP_LAST)
928 mono_async_invoke (MonoAsyncResult *ares)
930 ASyncCall *ac = (ASyncCall *)ares->object_data;
931 MonoThread *thread = NULL;
932 MonoObject *res, *exc = NULL;
933 MonoArray *out_args = NULL;
935 if (ares->execution_context) {
936 /* use captured ExecutionContext (if available) */
937 thread = mono_thread_current ();
938 MONO_OBJECT_SETREF (ares, original_context, thread->execution_context);
939 MONO_OBJECT_SETREF (thread, execution_context, ares->execution_context);
941 ares->original_context = NULL;
945 res = mono_message_invoke (ares->async_delegate, ac->msg, &exc, &out_args);
946 MONO_OBJECT_SETREF (ac, res, res);
947 MONO_OBJECT_SETREF (ac, msg->exc, exc);
948 MONO_OBJECT_SETREF (ac, out_args, out_args);
952 /* call async callback if cb_method != null*/
954 MonoObject *exc = NULL;
956 mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &exc);
957 /* 'exc' will be the previous ac->msg->exc if not NULL and not
958 * catched. If catched, this will be set to NULL and the
959 * exception will not be printed. */
960 MONO_OBJECT_SETREF (ac->msg, exc, exc);
963 /* restore original thread execution context if flow isn't suppressed, i.e. non null */
964 if (ares->original_context) {
965 MONO_OBJECT_SETREF (thread, execution_context, ares->original_context);
966 ares->original_context = NULL;
969 /* notify listeners */
970 mono_monitor_enter ((MonoObject *) ares);
971 if (ares->handle != NULL) {
972 ac->wait_event = (gsize) mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
973 SetEvent ((gpointer)(gsize)ac->wait_event);
975 mono_monitor_exit ((MonoObject *) ares);
977 EnterCriticalSection (&ares_lock);
978 mono_g_hash_table_remove (ares_htable, ares);
979 LeaveCriticalSection (&ares_lock);
983 mono_thread_pool_init ()
986 int threads_per_cpu = THREADS_PER_CPU;
988 if ((int) InterlockedCompareExchange (&tp_inited, 1, 0) == 1)
991 MONO_GC_REGISTER_ROOT (ares_htable);
992 MONO_GC_REGISTER_ROOT (socket_io_data.sock_to_state);
993 InitializeCriticalSection (&socket_io_data.io_lock);
994 InitializeCriticalSection (&ares_lock);
995 ares_htable = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_VALUE_GC);
996 job_added = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
997 g_assert (job_added != NULL);
998 GetSystemInfo (&info);
999 if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
1000 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
1001 if (threads_per_cpu <= 0)
1002 threads_per_cpu = THREADS_PER_CPU;
1005 mono_max_worker_threads = 20 + threads_per_cpu * info.dwNumberOfProcessors;
1007 async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
1008 g_assert (async_call_klass);
1012 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
1015 MonoDomain *domain = mono_domain_get ();
1016 MonoAsyncResult *ares;
1019 ac = (ASyncCall*)mono_object_new (mono_domain_get (), async_call_klass);
1020 MONO_OBJECT_SETREF (ac, msg, msg);
1021 MONO_OBJECT_SETREF (ac, state, state);
1023 if (async_callback) {
1024 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
1025 MONO_OBJECT_SETREF (ac, cb_target, async_callback);
1028 ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
1029 MONO_OBJECT_SETREF (ares, async_delegate, target);
1031 EnterCriticalSection (&ares_lock);
1032 mono_g_hash_table_insert (ares_htable, ares, ares);
1033 LeaveCriticalSection (&ares_lock);
1035 if (socket_io_filter (target, state)) {
1036 socket_io_add (ares, (MonoSocketAsyncResult *) state);
1040 start_thread_or_queue (ares);
1045 start_thread_or_queue (MonoAsyncResult *ares)
1049 busy = (int) InterlockedCompareExchange (&busy_worker_threads, 0, -1);
1050 worker = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1051 if (worker <= ++busy &&
1052 worker < mono_max_worker_threads) {
1053 InterlockedIncrement (&mono_worker_threads);
1054 InterlockedIncrement (&busy_worker_threads);
1055 mono_thread_create_internal (mono_get_root_domain (), async_invoke_thread, ares, TRUE);
1057 append_job (&mono_delegate_section, &async_call_queue, (MonoObject*)ares);
1058 ReleaseSemaphore (job_added, 1, NULL);
1063 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1070 /* check if already finished */
1071 mono_monitor_enter ((MonoObject *) ares);
1073 if (ares->endinvoke_called) {
1074 *exc = (MonoObject *)mono_exception_from_name (mono_defaults.corlib, "System",
1075 "InvalidOperationException");
1076 mono_monitor_exit ((MonoObject *) ares);
1080 ares->endinvoke_called = 1;
1081 ac = (ASyncCall *)ares->object_data;
1083 g_assert (ac != NULL);
1085 /* wait until we are really finished */
1086 if (!ares->completed) {
1087 if (ares->handle == NULL) {
1088 ac->wait_event = (gsize)CreateEvent (NULL, TRUE, FALSE, NULL);
1089 g_assert(ac->wait_event != 0);
1090 MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), (gpointer)(gsize)ac->wait_event));
1092 mono_monitor_exit ((MonoObject *) ares);
1093 WaitForSingleObjectEx ((gpointer)(gsize)ac->wait_event, INFINITE, TRUE);
1095 mono_monitor_exit ((MonoObject *) ares);
1098 *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1099 *out_args = ac->out_args;
1105 mono_thread_pool_cleanup (void)
1109 EnterCriticalSection (&mono_delegate_section);
1110 free_queue (&async_call_queue);
1111 release = (gint) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1112 LeaveCriticalSection (&mono_delegate_section);
1114 ReleaseSemaphore (job_added, release, NULL);
1116 socket_io_cleanup (&socket_io_data);
1120 append_job (CRITICAL_SECTION *cs, TPQueue *list, MonoObject *ar)
1122 EnterCriticalSection (cs);
1123 if (list->array && (list->next_elem < mono_array_length (list->array))) {
1124 mono_array_setref (list->array, list->next_elem, ar);
1126 LeaveCriticalSection (cs);
1130 MONO_GC_REGISTER_ROOT (list->array);
1131 list->array = mono_array_new (mono_get_root_domain (), mono_defaults.object_class, 16);
1133 int count = list->next_elem - list->first_elem;
1134 /* slide the array or create a larger one if it's full */
1135 if (list->first_elem) {
1136 mono_array_memcpy_refs (list->array, 0, list->array, list->first_elem, count);
1138 MonoArray *newa = mono_array_new (mono_get_root_domain (), mono_defaults.object_class, mono_array_length (list->array) * 2);
1139 mono_array_memcpy_refs (newa, 0, list->array, list->first_elem, count);
1142 list->first_elem = 0;
1143 list->next_elem = count;
1145 mono_array_setref (list->array, list->next_elem, ar);
1147 LeaveCriticalSection (cs);
1151 dequeue_job (CRITICAL_SECTION *cs, TPQueue *list)
1156 EnterCriticalSection (cs);
1157 if (!list->array || list->first_elem == list->next_elem) {
1158 LeaveCriticalSection (cs);
1161 ar = mono_array_get (list->array, MonoObject*, list->first_elem);
1163 count = list->next_elem - list->first_elem;
1164 /* reduce the size of the array if it's mostly empty */
1165 if (mono_array_length (list->array) > 16 && count < (mono_array_length (list->array) / 3)) {
1166 MonoArray *newa = mono_array_new (mono_get_root_domain (), mono_defaults.object_class, mono_array_length (list->array) / 2);
1167 mono_array_memcpy_refs (newa, 0, list->array, list->first_elem, count);
1169 list->first_elem = 0;
1170 list->next_elem = count;
1172 LeaveCriticalSection (cs);
1178 free_queue (TPQueue *list)
1181 list->first_elem = list->next_elem = 0;
1185 async_invoke_thread (gpointer data)
1191 thread = mono_thread_current ();
1192 thread->threadpool_thread = TRUE;
1193 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
1196 MonoAsyncResult *ar;
1198 ar = (MonoAsyncResult *) data;
1200 /* worker threads invokes methods in different domains,
1201 * so we need to set the right domain here */
1202 domain = ((MonoObject *)ar)->vtable->domain;
1203 mono_thread_push_appdomain_ref (domain);
1204 if (mono_domain_set (domain, FALSE)) {
1207 mono_async_invoke (ar);
1208 ac = (ASyncCall *) ar->object_data;
1210 if (ac->msg->exc != NULL)
1211 mono_unhandled_exception (ac->msg->exc);
1213 mono_domain_set (mono_get_root_domain (), TRUE);
1215 mono_thread_pop_appdomain_ref ();
1216 InterlockedDecrement (&busy_worker_threads);
1219 data = dequeue_job (&mono_delegate_section, &async_call_queue);
1223 int timeout = 10000;
1224 guint32 start_time = mono_msec_ticks ();
1227 wr = WaitForSingleObjectEx (job_added, (guint32)timeout, TRUE);
1228 if (THREAD_WANTS_A_BREAK (thread))
1229 mono_thread_interruption_checkpoint ();
1231 timeout -= mono_msec_ticks () - start_time;
1233 if (wr != WAIT_TIMEOUT)
1234 data = dequeue_job (&mono_delegate_section, &async_call_queue);
1236 while (!data && timeout > 0);
1240 workers = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1241 min = (int) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
1243 while (!data && workers <= min) {
1244 WaitForSingleObjectEx (job_added, INFINITE, TRUE);
1245 if (THREAD_WANTS_A_BREAK (thread))
1246 mono_thread_interruption_checkpoint ();
1248 data = dequeue_job (&mono_delegate_section, &async_call_queue);
1249 workers = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1250 min = (int) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
1255 InterlockedDecrement (&mono_worker_threads);
1259 InterlockedIncrement (&busy_worker_threads);
1262 g_assert_not_reached ();
1266 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
1270 MONO_ARCH_SAVE_REGS;
1272 busy = (gint) InterlockedCompareExchange (&busy_worker_threads, 0, -1);
1273 busy_io = (gint) InterlockedCompareExchange (&busy_io_worker_threads, 0, -1);
1274 *workerThreads = mono_max_worker_threads - busy;
1275 *completionPortThreads = mono_io_max_worker_threads - busy_io;
1279 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
1281 MONO_ARCH_SAVE_REGS;
1283 *workerThreads = mono_max_worker_threads;
1284 *completionPortThreads = mono_io_max_worker_threads;
1288 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
1290 gint workers, workers_io;
1292 MONO_ARCH_SAVE_REGS;
1294 workers = (gint) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
1295 workers_io = (gint) InterlockedCompareExchange (&mono_io_min_worker_threads, 0, -1);
1297 *workerThreads = workers;
1298 *completionPortThreads = workers_io;
1302 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
1304 MONO_ARCH_SAVE_REGS;
1306 if (workerThreads < 0 || workerThreads > mono_max_worker_threads)
1309 if (completionPortThreads < 0 || completionPortThreads > mono_io_max_worker_threads)
1312 InterlockedExchange (&mono_min_worker_threads, workerThreads);
1313 InterlockedExchange (&mono_io_min_worker_threads, completionPortThreads);
1314 /* FIXME: should actually start the idle threads if needed */
1319 ves_icall_System_Threading_ThreadPool_SetMaxThreads (gint workerThreads, gint completionPortThreads)
1321 MONO_ARCH_SAVE_REGS;
1323 if (workerThreads < mono_max_worker_threads)
1326 if (completionPortThreads < mono_io_max_worker_threads)
1329 InterlockedExchange (&mono_max_worker_threads, workerThreads);
1330 InterlockedExchange (&mono_io_max_worker_threads, completionPortThreads);