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/marshal.h>
31 #include <mono/metadata/socket-io.h>
32 #include <mono/io-layer/io-layer.h>
33 #include <mono/os/gc_wrapper.h>
36 #include <sys/types.h>
41 #include <mono/utils/mono-poll.h>
43 #include <sys/epoll.h>
46 #include "mono/io-layer/socket-wrappers.h"
48 #include "threadpool.h"
50 #define THREAD_WANTS_A_BREAK(t) ((t->state & (ThreadState_StopRequested | \
51 ThreadState_SuspendRequested)) != 0)
55 /* maximum number of worker threads */
56 static int mono_max_worker_threads;
57 static int mono_min_worker_threads;
58 static int mono_io_max_worker_threads;
60 /* current number of worker threads */
61 static int mono_worker_threads = 0;
62 static int io_worker_threads = 0;
64 /* current number of busy threads */
65 static int busy_worker_threads = 0;
66 static int busy_io_worker_threads;
68 /* mono_thread_pool_init called */
71 /* we use this to store a reference to the AsyncResult to avoid GC */
72 static MonoGHashTable *ares_htable = NULL;
74 static CRITICAL_SECTION ares_lock;
75 static CRITICAL_SECTION io_queue_lock;
76 static int pending_io_items;
79 CRITICAL_SECTION io_lock; /* access to sock_to_state */
82 GHashTable *sock_to_state;
84 HANDLE new_sem; /* access to newpfd and write side of the pipe */
86 gboolean epoll_disabled;
92 static SocketIOData socket_io_data;
95 static HANDLE job_added;
96 static HANDLE io_job_added;
98 /* Keep in sync with the System.MonoAsyncCall class which provides GC tracking */
101 MonoMethodMessage *msg;
102 MonoMethod *cb_method;
103 MonoDelegate *cb_target;
107 /* This is a HANDLE, we use guint64 so the managed object layout remains constant */
111 static void async_invoke_thread (gpointer data);
112 static void append_job (CRITICAL_SECTION *cs, GList **plist, gpointer ar);
113 static void start_thread_or_queue (MonoAsyncResult *ares);
114 static void mono_async_invoke (MonoAsyncResult *ares);
115 static gpointer dequeue_job (CRITICAL_SECTION *cs, GList **plist);
117 static GList *async_call_queue = NULL;
118 static GList *async_io_queue = NULL;
120 static MonoClass *async_call_klass;
121 static MonoClass *socket_async_call_klass;
122 static MonoClass *process_async_call_klass;
124 #define INIT_POLLFD(a, b, c) {(a)->fd = b; (a)->events = c; (a)->revents = 0;}
133 AIO_OP_RECV_JUST_CALLBACK,
134 AIO_OP_SEND_JUST_CALLBACK,
140 socket_io_cleanup (SocketIOData *data)
144 if (data->inited == 0)
147 EnterCriticalSection (&data->io_lock);
149 #ifdef PLATFORM_WIN32
150 closesocket (data->pipe [0]);
151 closesocket (data->pipe [1]);
153 close (data->pipe [0]);
154 close (data->pipe [1]);
159 CloseHandle (data->new_sem);
160 data->new_sem = NULL;
161 g_hash_table_destroy (data->sock_to_state);
162 data->sock_to_state = NULL;
163 g_list_free (async_io_queue);
164 async_io_queue = NULL;
165 release = (gint) InterlockedCompareExchange (&io_worker_threads, 0, -1);
167 ReleaseSemaphore (io_job_added, release, NULL);
168 g_free (data->newpfd);
171 if (FALSE == data->epoll_disabled)
172 close (data->epollfd);
174 LeaveCriticalSection (&data->io_lock);
178 get_event_from_state (MonoSocketAsyncResult *state)
180 switch (state->operation) {
183 case AIO_OP_RECV_JUST_CALLBACK:
184 case AIO_OP_RECEIVEFROM:
185 case AIO_OP_READPIPE:
188 case AIO_OP_SEND_JUST_CALLBACK:
192 default: /* Should never happen */
193 g_print ("get_event_from_state: unknown value in switch!!!\n");
199 get_events_from_list (GSList *list)
201 MonoSocketAsyncResult *state;
204 while (list && list->data) {
205 state = (MonoSocketAsyncResult *) list->data;
206 events |= get_event_from_state (state);
213 #define ICALL_RECV(x) ves_icall_System_Net_Sockets_Socket_Receive_internal (\
214 (SOCKET) x->handle, x->buffer, x->offset, x->size,\
215 x->socket_flags, &x->error);
217 #define ICALL_SEND(x) ves_icall_System_Net_Sockets_Socket_Send_internal (\
218 (SOCKET) x->handle, x->buffer, x->offset, x->size,\
219 x->socket_flags, &x->error);
222 async_invoke_io_thread (gpointer data)
226 thread = mono_thread_current ();
227 thread->threadpool_thread = TRUE;
228 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
231 MonoSocketAsyncResult *state;
234 state = (MonoSocketAsyncResult *) data;
236 InterlockedDecrement (&pending_io_items);
238 switch (state->operation) {
240 state->total = ICALL_RECV (state);
243 state->total = ICALL_SEND (state);
247 /* worker threads invokes methods in different domains,
248 * so we need to set the right domain here */
249 domain = ((MonoObject *)ar)->vtable->domain;
250 mono_thread_push_appdomain_ref (domain);
251 if (mono_domain_set (domain, FALSE)) {
254 mono_async_invoke (ar);
255 ac = (ASyncCall *) ar->object_data;
257 if (ac->msg->exc != NULL)
258 mono_unhandled_exception (ac->msg->exc);
260 mono_domain_set (mono_get_root_domain (), TRUE);
262 mono_thread_pop_appdomain_ref ();
263 InterlockedDecrement (&busy_io_worker_threads);
266 data = dequeue_job (&io_queue_lock, &async_io_queue);
271 guint32 start_time = GetTickCount ();
274 wr = WaitForSingleObjectEx (io_job_added, (guint32)timeout, TRUE);
275 if (THREAD_WANTS_A_BREAK (thread))
276 mono_thread_interruption_checkpoint ();
278 timeout -= GetTickCount () - start_time;
280 if (wr != WAIT_TIMEOUT)
281 data = dequeue_job (&io_queue_lock, &async_io_queue);
283 while (!data && timeout > 0);
287 if (InterlockedDecrement (&io_worker_threads) < 2) {
288 /* If we have pending items, keep the thread alive */
289 if (InterlockedCompareExchange (&pending_io_items, 0, 0) != 0) {
290 InterlockedIncrement (&io_worker_threads);
297 InterlockedIncrement (&busy_io_worker_threads);
300 g_assert_not_reached ();
304 start_io_thread_or_queue (MonoSocketAsyncResult *ares)
309 busy = (int) InterlockedCompareExchange (&busy_io_worker_threads, 0, -1);
310 worker = (int) InterlockedCompareExchange (&io_worker_threads, 0, -1);
311 if (worker <= ++busy &&
312 worker < mono_io_max_worker_threads) {
313 InterlockedIncrement (&busy_io_worker_threads);
314 InterlockedIncrement (&io_worker_threads);
315 domain = ((ares) ? ((MonoObject *) ares)->vtable->domain : mono_domain_get ());
316 mono_thread_create (mono_get_root_domain (), async_invoke_io_thread, ares);
318 append_job (&io_queue_lock, &async_io_queue, ares);
319 ReleaseSemaphore (io_job_added, 1, NULL);
324 process_io_event (GSList *list, int event)
326 MonoSocketAsyncResult *state;
332 state = (MonoSocketAsyncResult *) list->data;
333 if (get_event_from_state (state) == event)
340 oldlist = g_slist_remove_link (oldlist, list);
341 g_slist_free_1 (list);
343 g_print ("Dispatching event %d on socket %d\n", event, state->handle);
345 InterlockedIncrement (&pending_io_items);
346 start_io_thread_or_queue (state);
353 mark_bad_fds (mono_pollfd *pfds, int nfds)
359 for (i = 0; i < nfds; i++) {
364 ret = mono_poll (pfd, 1, 0);
365 if (ret == -1 && errno == EBADF) {
366 pfd->revents |= MONO_POLLNVAL;
368 } else if (ret == 1) {
377 socket_io_poll_main (gpointer p)
379 #define INITIAL_POLLFD_SIZE 1024
380 #define POLL_ERRORS (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL)
381 SocketIOData *data = p;
388 thread = mono_thread_current ();
389 thread->threadpool_thread = TRUE;
390 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
392 allocated = INITIAL_POLLFD_SIZE;
393 pfds = g_new0 (mono_pollfd, allocated);
394 INIT_POLLFD (pfds, data->pipe [0], MONO_POLLIN);
395 for (i = 1; i < allocated; i++)
396 INIT_POLLFD (&pfds [i], -1, 0);
406 if (THREAD_WANTS_A_BREAK (thread))
407 mono_thread_interruption_checkpoint ();
410 nsock = mono_poll (pfds, maxfd, -1);
411 } while (nsock == -1 && errno == EINTR);
414 * Apart from EINTR, we only check EBADF, for the rest:
415 * EINVAL: mono_poll() 'protects' us from descriptor
416 * numbers above the limit if using select() by marking
417 * then as MONO_POLLERR. If a system poll() is being
418 * used, the number of descriptor we're passing will not
419 * be over sysconf(_SC_OPEN_MAX), as the error would have
420 * happened when opening.
422 * EFAULT: we own the memory pointed by pfds.
423 * ENOMEM: we're doomed anyway
427 if (nsock == -1 && errno == EBADF) {
428 pfds->revents = 0; /* Just in case... */
429 nsock = mark_bad_fds (pfds, maxfd);
432 if ((pfds->revents & POLL_ERRORS) != 0) {
433 /* We're supposed to die now, as the pipe has been closed */
435 socket_io_cleanup (data);
439 /* Got a new socket */
440 if ((pfds->revents & MONO_POLLIN) != 0) {
443 for (i = 1; i < allocated; i++) {
445 if (pfd->fd == -1 || pfd->fd == data->newpfd->fd)
449 if (i == allocated) {
454 allocated = allocated * 2;
455 pfds = g_renew (mono_pollfd, oldfd, allocated);
457 for (; i < allocated; i++)
458 INIT_POLLFD (&pfds [i], -1, 0);
460 #ifndef PLATFORM_WIN32
461 nread = read (data->pipe [0], one, 1);
463 nread = recv ((SOCKET) data->pipe [0], one, 1, 0);
467 return; /* we're closed */
470 INIT_POLLFD (&pfds [i], data->newpfd->fd, data->newpfd->events);
471 ReleaseSemaphore (data->new_sem, 1, NULL);
480 EnterCriticalSection (&data->io_lock);
481 if (data->inited == 0) {
483 LeaveCriticalSection (&data->io_lock);
484 return; /* cleanup called */
487 for (i = 1; i < maxfd && nsock > 0; i++) {
489 if (pfd->fd == -1 || pfd->revents == 0)
493 list = g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
494 if (list != NULL && (pfd->revents & (MONO_POLLIN | POLL_ERRORS)) != 0) {
495 list = process_io_event (list, MONO_POLLIN);
498 if (list != NULL && (pfd->revents & (MONO_POLLOUT | POLL_ERRORS)) != 0) {
499 list = process_io_event (list, MONO_POLLOUT);
503 g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (pfd->fd), list);
504 pfd->events = get_events_from_list (list);
506 g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
512 LeaveCriticalSection (&data->io_lock);
517 #define EPOLL_ERRORS (EPOLLERR | EPOLLHUP)
519 socket_io_epoll_main (gpointer p)
524 struct epoll_event *events, *evt;
525 const int nevents = 512;
529 epollfd = data->epollfd;
530 thread = mono_thread_current ();
531 thread->threadpool_thread = TRUE;
532 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
533 events = g_new0 (struct epoll_event, nevents);
538 if (THREAD_WANTS_A_BREAK (thread))
539 mono_thread_interruption_checkpoint ();
542 g_print ("epoll_wait init\n");
544 ready = epoll_wait (epollfd, events, nevents, -1);
548 g_print ("epoll_wait end with %d ready sockets (%d %s).\n", ready, err, (err) ? g_strerror (err) : "");
552 } while (ready == -1 && errno == EINTR);
558 g_warning ("epoll_wait: %d %s\n", err, g_strerror (err));
564 EnterCriticalSection (&data->io_lock);
565 if (data->inited == 0) {
567 g_print ("data->inited == 0\n");
571 return; /* cleanup called */
574 for (i = 0; i < ready; i++) {
580 list = g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
582 g_print ("Event %d on %d list length: %d\n", evt->events, fd, g_slist_length (list));
584 if (list != NULL && (evt->events & (EPOLLIN | EPOLL_ERRORS)) != 0) {
585 list = process_io_event (list, MONO_POLLIN);
588 if (list != NULL && (evt->events & (EPOLLOUT | EPOLL_ERRORS)) != 0) {
589 list = process_io_event (list, MONO_POLLOUT);
593 g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (fd), list);
594 evt->events = get_events_from_list (list);
596 g_print ("MOD %d to %d\n", fd, evt->events);
598 if (epoll_ctl (epollfd, EPOLL_CTL_MOD, fd, evt)) {
599 if (epoll_ctl (epollfd, EPOLL_CTL_ADD, fd, evt) == -1) {
602 g_message ("epoll_ctl(MOD): %d %s fd: %d events: %d", err, g_strerror (err), fd, evt->events);
608 g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (fd));
610 g_print ("DEL %d\n", fd);
612 epoll_ctl (epollfd, EPOLL_CTL_DEL, fd, evt);
615 LeaveCriticalSection (&data->io_lock);
621 * select/poll wake up when a socket is closed, but epoll just removes
622 * the socket from its internal list without notification.
625 mono_thread_pool_remove_socket (int sock)
629 MonoSocketAsyncResult *state;
631 if (socket_io_data.epoll_disabled == TRUE || socket_io_data.inited == FALSE)
634 EnterCriticalSection (&socket_io_data.io_lock);
635 list = g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
637 g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
639 LeaveCriticalSection (&socket_io_data.io_lock);
642 state = (MonoSocketAsyncResult *) list->data;
643 if (state->operation == AIO_OP_RECEIVE)
644 state->operation = AIO_OP_RECV_JUST_CALLBACK;
645 else if (state->operation == AIO_OP_SEND)
646 state->operation = AIO_OP_SEND_JUST_CALLBACK;
648 next = g_slist_remove_link (list, list);
649 list = process_io_event (list, MONO_POLLIN);
651 process_io_event (list, MONO_POLLOUT);
658 #ifdef PLATFORM_WIN32
660 connect_hack (gpointer x)
662 struct sockaddr_in *addr = (struct sockaddr_in *) x;
665 while (connect ((SOCKET) socket_io_data.pipe [1], (SOCKADDR *) addr, sizeof (struct sockaddr_in))) {
668 g_warning ("Error initializing async. sockets %d.\n", WSAGetLastError ());
669 g_assert (WSAGetLastError ());
676 socket_io_init (SocketIOData *data)
678 #ifdef PLATFORM_WIN32
679 struct sockaddr_in server;
680 struct sockaddr_in client;
686 inited = InterlockedCompareExchange (&data->inited, -1, -1);
690 EnterCriticalSection (&data->io_lock);
691 inited = InterlockedCompareExchange (&data->inited, -1, -1);
693 LeaveCriticalSection (&data->io_lock);
698 data->epoll_disabled = (g_getenv ("MONO_DISABLE_AIO") != NULL);
699 if (FALSE == data->epoll_disabled) {
700 data->epollfd = epoll_create (256);
701 data->epoll_disabled = (data->epollfd == -1);
702 if (data->epoll_disabled && g_getenv ("MONO_DEBUG"))
703 g_message ("epoll_create() failed. Using plain poll().");
708 data->epoll_disabled = TRUE;
711 #ifndef PLATFORM_WIN32
712 if (data->epoll_disabled) {
713 if (pipe (data->pipe) != 0) {
723 srv = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
724 g_assert (srv != INVALID_SOCKET);
725 data->pipe [1] = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
726 g_assert (data->pipe [1] != INVALID_SOCKET);
728 server.sin_family = AF_INET;
729 server.sin_addr.s_addr = inet_addr ("127.0.0.1");
731 if (bind (srv, (SOCKADDR *) &server, sizeof (server))) {
732 g_print ("%d\n", WSAGetLastError ());
736 len = sizeof (server);
737 getsockname (srv, (SOCKADDR *) &server, &len);
739 mono_thread_create (mono_get_root_domain (), connect_hack, &server);
740 len = sizeof (server);
741 data->pipe [0] = accept (srv, (SOCKADDR *) &client, &len);
742 g_assert (data->pipe [0] != INVALID_SOCKET);
745 mono_io_max_worker_threads = mono_max_worker_threads / 2;
746 if (mono_io_max_worker_threads < 10)
747 mono_io_max_worker_threads = 10;
749 data->sock_to_state = g_hash_table_new (g_direct_hash, g_direct_equal);
751 if (data->epoll_disabled) {
752 data->new_sem = CreateSemaphore (NULL, 1, 1, NULL);
753 g_assert (data->new_sem != NULL);
755 io_job_added = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
756 g_assert (io_job_added != NULL);
757 InitializeCriticalSection (&io_queue_lock);
758 if (data->epoll_disabled) {
759 mono_thread_create (mono_get_root_domain (), socket_io_poll_main, data);
763 mono_thread_create (mono_get_root_domain (), socket_io_epoll_main, data);
766 InterlockedCompareExchange (&data->inited, 1, 0);
767 LeaveCriticalSection (&data->io_lock);
771 socket_io_add_poll (MonoSocketAsyncResult *state)
776 SocketIOData *data = &socket_io_data;
778 #if defined(PLATFORM_MACOSX) || defined(PLATFORM_BSD6) || defined(PLATFORM_WIN32)
779 /* select() for connect() does not work well on the Mac. Bug #75436. */
780 /* Bug #77637 for the BSD 6 case */
781 /* Bug #78888 for the Windows case */
782 if (state->operation == AIO_OP_CONNECT && state->blocking == TRUE) {
783 start_io_thread_or_queue (state);
787 WaitForSingleObject (data->new_sem, INFINITE);
788 if (data->newpfd == NULL)
789 data->newpfd = g_new0 (mono_pollfd, 1);
791 EnterCriticalSection (&data->io_lock);
792 /* FIXME: 64 bit issue: handle can be a pointer on windows? */
793 list = g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (state->handle));
794 /* FIXME: GC issue: state is an object stored in a GList */
796 list = g_slist_alloc ();
799 list = g_slist_append (list, state);
802 events = get_events_from_list (list);
803 INIT_POLLFD (data->newpfd, GPOINTER_TO_INT (state->handle), events);
804 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 = g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
828 /* FIXME: GC issue: state is an object stored in a GList */
830 list = g_slist_alloc ();
832 epoll_op = EPOLL_CTL_ADD;
834 list = g_slist_append (list, state);
835 epoll_op = EPOLL_CTL_MOD;
838 ievt = get_events_from_list (list);
839 if ((ievt & MONO_POLLIN) != 0)
840 event.events |= EPOLLIN;
841 if ((ievt & MONO_POLLOUT) != 0)
842 event.events |= EPOLLOUT;
844 g_hash_table_replace (data->sock_to_state, state->handle, list);
847 g_print ("%s %d with %d\n", epoll_op == EPOLL_CTL_ADD ? "ADD" : "MOD", fd, event.events);
849 if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
851 if (epoll_op == EPOLL_CTL_ADD && err == EEXIST) {
852 epoll_op = EPOLL_CTL_MOD;
853 if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
854 g_message ("epoll_ctl(MOD): %d %s\n", err, g_strerror (err));
859 LeaveCriticalSection (&data->io_lock);
865 socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
867 socket_io_init (&socket_io_data);
868 MONO_OBJECT_SETREF (state, ares, ares);
870 if (socket_io_data.epoll_disabled == FALSE) {
871 if (socket_io_add_epoll (state))
875 socket_io_add_poll (state);
879 socket_io_filter (MonoObject *target, MonoObject *state)
882 MonoSocketAsyncResult *sock_res = (MonoSocketAsyncResult *) state;
885 if (target == NULL || state == NULL)
888 if (socket_async_call_klass == NULL) {
889 klass = target->vtable->klass;
890 /* Check if it's SocketAsyncCall in System.Net.Sockets
891 * FIXME: check the assembly is signed correctly for extra care
893 if (klass->name [0] == 'S' && strcmp (klass->name, "SocketAsyncCall") == 0
894 && strcmp (mono_image_get_name (klass->image), "System") == 0
895 && klass->nested_in && strcmp (klass->nested_in->name, "Socket") == 0)
896 socket_async_call_klass = klass;
899 if (process_async_call_klass == NULL) {
900 klass = target->vtable->klass;
901 /* Check if it's AsyncReadHandler in System.Diagnostics.Process
902 * FIXME: check the assembly is signed correctly for extra care
904 if (klass->name [0] == 'A' && strcmp (klass->name, "AsyncReadHandler") == 0
905 && strcmp (mono_image_get_name (klass->image), "System") == 0
906 && klass->nested_in && strcmp (klass->nested_in->name, "Process") == 0)
907 process_async_call_klass = klass;
909 /* return both when socket_async_call_klass has not been seen yet and when
910 * the object is not an instance of the class.
912 if (target->vtable->klass != socket_async_call_klass && target->vtable->klass != process_async_call_klass)
915 op = sock_res->operation;
916 if (op < AIO_OP_FIRST || op >= AIO_OP_LAST)
923 mono_async_invoke (MonoAsyncResult *ares)
925 ASyncCall *ac = (ASyncCall *)ares->object_data;
926 MonoThread *thread = NULL;
927 MonoObject *res, *exc = NULL;
928 MonoArray *out_args = NULL;
930 if (ares->execution_context) {
931 /* use captured ExecutionContext (if available) */
932 thread = mono_thread_current ();
933 MONO_OBJECT_SETREF (ares, original_context, thread->execution_context);
934 MONO_OBJECT_SETREF (thread, execution_context, ares->execution_context);
936 ares->original_context = NULL;
940 res = mono_message_invoke (ares->async_delegate, ac->msg, &exc, &out_args);
941 MONO_OBJECT_SETREF (ac, res, res);
942 MONO_OBJECT_SETREF (ac, msg->exc, exc);
943 MONO_OBJECT_SETREF (ac, out_args, out_args);
947 /* call async callback if cb_method != null*/
949 MonoObject *exc = NULL;
951 mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &exc);
952 /* 'exc' will be the previous ac->msg->exc if not NULL and not
953 * catched. If catched, this will be set to NULL and the
954 * exception will not be printed. */
955 MONO_OBJECT_SETREF (ac->msg, exc, exc);
958 /* restore original thread execution context if flow isn't suppressed, i.e. non null */
959 if (ares->original_context) {
960 MONO_OBJECT_SETREF (thread, execution_context, ares->original_context);
961 ares->original_context = NULL;
964 /* notify listeners */
965 mono_monitor_enter ((MonoObject *) ares);
966 if (ares->handle != NULL) {
967 ac->wait_event = (gsize)((MonoWaitHandle *) ares->handle)->handle;
968 SetEvent ((gpointer)(gsize)ac->wait_event);
970 mono_monitor_exit ((MonoObject *) ares);
972 EnterCriticalSection (&ares_lock);
973 mono_g_hash_table_remove (ares_htable, ares);
974 LeaveCriticalSection (&ares_lock);
978 mono_thread_pool_init ()
981 int threads_per_cpu = THREADS_PER_CPU;
983 if ((int) InterlockedCompareExchange (&tp_inited, 1, 0) == 1)
986 MONO_GC_REGISTER_ROOT (ares_htable);
987 InitializeCriticalSection (&socket_io_data.io_lock);
988 InitializeCriticalSection (&ares_lock);
989 ares_htable = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_VALUE_GC);
990 job_added = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
991 g_assert (job_added != NULL);
992 GetSystemInfo (&info);
993 if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
994 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
995 if (threads_per_cpu <= 0)
996 threads_per_cpu = THREADS_PER_CPU;
999 mono_max_worker_threads = 20 + threads_per_cpu * info.dwNumberOfProcessors;
1001 async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
1002 g_assert (async_call_klass);
1006 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
1009 MonoDomain *domain = mono_domain_get ();
1010 MonoAsyncResult *ares;
1013 ac = (ASyncCall*)mono_object_new (mono_domain_get (), async_call_klass);
1014 MONO_OBJECT_SETREF (ac, msg, msg);
1015 MONO_OBJECT_SETREF (ac, state, state);
1017 if (async_callback) {
1018 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
1019 MONO_OBJECT_SETREF (ac, cb_target, async_callback);
1022 ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
1023 MONO_OBJECT_SETREF (ares, async_delegate, target);
1025 EnterCriticalSection (&ares_lock);
1026 mono_g_hash_table_insert (ares_htable, ares, ares);
1027 LeaveCriticalSection (&ares_lock);
1029 if (socket_io_filter (target, state)) {
1030 socket_io_add (ares, (MonoSocketAsyncResult *) state);
1034 start_thread_or_queue (ares);
1039 start_thread_or_queue (MonoAsyncResult *ares)
1043 busy = (int) InterlockedCompareExchange (&busy_worker_threads, 0, -1);
1044 worker = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1045 if (worker <= ++busy &&
1046 worker < mono_max_worker_threads) {
1047 InterlockedIncrement (&mono_worker_threads);
1048 InterlockedIncrement (&busy_worker_threads);
1049 mono_thread_create (mono_get_root_domain (), async_invoke_thread, ares);
1051 append_job (&mono_delegate_section, &async_call_queue, ares);
1052 ReleaseSemaphore (job_added, 1, NULL);
1057 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1064 /* check if already finished */
1065 mono_monitor_enter ((MonoObject *) ares);
1067 if (ares->endinvoke_called) {
1068 *exc = (MonoObject *)mono_exception_from_name (mono_defaults.corlib, "System",
1069 "InvalidOperationException");
1070 mono_monitor_exit ((MonoObject *) ares);
1074 ares->endinvoke_called = 1;
1075 ac = (ASyncCall *)ares->object_data;
1077 g_assert (ac != NULL);
1079 /* wait until we are really finished */
1080 if (!ares->completed) {
1081 if (ares->handle == NULL) {
1082 ac->wait_event = (gsize)CreateEvent (NULL, TRUE, FALSE, NULL);
1083 g_assert(ac->wait_event != 0);
1084 MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), (gpointer)(gsize)ac->wait_event));
1086 mono_monitor_exit ((MonoObject *) ares);
1087 WaitForSingleObjectEx ((gpointer)(gsize)ac->wait_event, INFINITE, TRUE);
1089 mono_monitor_exit ((MonoObject *) ares);
1092 *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1093 *out_args = ac->out_args;
1099 mono_thread_pool_cleanup (void)
1103 EnterCriticalSection (&mono_delegate_section);
1104 g_list_free (async_call_queue);
1105 async_call_queue = NULL;
1106 release = (gint) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1107 LeaveCriticalSection (&mono_delegate_section);
1109 ReleaseSemaphore (job_added, release, NULL);
1111 socket_io_cleanup (&socket_io_data);
1114 /* FIXME: GC: adds managed objects to the list... */
1116 append_job (CRITICAL_SECTION *cs, GList **plist, gpointer ar)
1120 EnterCriticalSection (cs);
1123 list = g_list_append (list, ar);
1125 for (tmp = list; tmp && tmp->data != NULL; tmp = tmp->next);
1127 list = g_list_append (list, ar);
1133 LeaveCriticalSection (cs);
1137 dequeue_job (CRITICAL_SECTION *cs, GList **plist)
1140 GList *tmp, *tmp2, *list;
1142 EnterCriticalSection (cs);
1149 for (tmp2 = tmp; tmp2->next != NULL; tmp2 = tmp2->next);
1158 LeaveCriticalSection (cs);
1164 async_invoke_thread (gpointer data)
1170 thread = mono_thread_current ();
1171 thread->threadpool_thread = TRUE;
1172 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
1175 MonoAsyncResult *ar;
1177 ar = (MonoAsyncResult *) data;
1179 /* worker threads invokes methods in different domains,
1180 * so we need to set the right domain here */
1181 domain = ((MonoObject *)ar)->vtable->domain;
1182 mono_thread_push_appdomain_ref (domain);
1183 if (mono_domain_set (domain, FALSE)) {
1186 mono_async_invoke (ar);
1187 ac = (ASyncCall *) ar->object_data;
1189 if (ac->msg->exc != NULL)
1190 mono_unhandled_exception (ac->msg->exc);
1192 mono_domain_set (mono_get_root_domain (), TRUE);
1194 mono_thread_pop_appdomain_ref ();
1195 InterlockedDecrement (&busy_worker_threads);
1198 data = dequeue_job (&mono_delegate_section, &async_call_queue);
1202 int timeout = 10000;
1203 guint32 start_time = GetTickCount ();
1206 wr = WaitForSingleObjectEx (job_added, (guint32)timeout, TRUE);
1207 if (THREAD_WANTS_A_BREAK (thread))
1208 mono_thread_interruption_checkpoint ();
1210 timeout -= GetTickCount () - start_time;
1212 if (wr != WAIT_TIMEOUT)
1213 data = dequeue_job (&mono_delegate_section, &async_call_queue);
1215 while (!data && timeout > 0);
1219 workers = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1220 min = (int) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
1222 while (!data && workers <= min) {
1223 WaitForSingleObjectEx (job_added, INFINITE, TRUE);
1224 if (THREAD_WANTS_A_BREAK (thread))
1225 mono_thread_interruption_checkpoint ();
1227 data = dequeue_job (&mono_delegate_section, &async_call_queue);
1228 workers = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1229 min = (int) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
1234 InterlockedDecrement (&mono_worker_threads);
1238 InterlockedIncrement (&busy_worker_threads);
1241 g_assert_not_reached ();
1245 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
1249 MONO_ARCH_SAVE_REGS;
1251 busy = (gint) InterlockedCompareExchange (&busy_worker_threads, 0, -1);
1252 *workerThreads = mono_max_worker_threads - busy;
1253 *completionPortThreads = 0;
1257 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
1259 MONO_ARCH_SAVE_REGS;
1261 *workerThreads = mono_max_worker_threads;
1262 *completionPortThreads = 0;
1266 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
1270 MONO_ARCH_SAVE_REGS;
1272 workers = (gint) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
1273 *workerThreads = workers;
1274 *completionPortThreads = 0;
1278 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
1280 MONO_ARCH_SAVE_REGS;
1282 if (workerThreads < 0 || workerThreads > mono_max_worker_threads)
1284 InterlockedExchange (&mono_min_worker_threads, workerThreads);
1285 /* FIXME: should actually start the idle threads if needed */