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;
123 #define INIT_POLLFD(a, b, c) {(a)->fd = b; (a)->events = c; (a)->revents = 0;}
132 AIO_OP_RECV_JUST_CALLBACK,
133 AIO_OP_SEND_JUST_CALLBACK,
138 socket_io_cleanup (SocketIOData *data)
142 if (data->inited == 0)
145 EnterCriticalSection (&data->io_lock);
147 #ifdef PLATFORM_WIN32
148 closesocket (data->pipe [0]);
149 closesocket (data->pipe [1]);
151 close (data->pipe [0]);
152 close (data->pipe [1]);
157 CloseHandle (data->new_sem);
158 data->new_sem = NULL;
159 g_hash_table_destroy (data->sock_to_state);
160 data->sock_to_state = NULL;
161 g_list_free (async_io_queue);
162 async_io_queue = NULL;
163 release = (gint) InterlockedCompareExchange (&io_worker_threads, 0, -1);
165 ReleaseSemaphore (io_job_added, release, NULL);
166 g_free (data->newpfd);
169 if (FALSE == data->epoll_disabled)
170 close (data->epollfd);
172 LeaveCriticalSection (&data->io_lock);
176 get_event_from_state (MonoSocketAsyncResult *state)
178 switch (state->operation) {
181 case AIO_OP_RECV_JUST_CALLBACK:
182 case AIO_OP_RECEIVEFROM:
185 case AIO_OP_SEND_JUST_CALLBACK:
189 default: /* Should never happen */
190 g_print ("get_event_from_state: unknown value in switch!!!\n");
196 get_events_from_list (GSList *list)
198 MonoSocketAsyncResult *state;
201 while (list && list->data) {
202 state = (MonoSocketAsyncResult *) list->data;
203 events |= get_event_from_state (state);
210 #define ICALL_RECV(x) ves_icall_System_Net_Sockets_Socket_Receive_internal (\
211 (SOCKET) x->handle, x->buffer, x->offset, x->size,\
212 x->socket_flags, &x->error);
214 #define ICALL_SEND(x) ves_icall_System_Net_Sockets_Socket_Send_internal (\
215 (SOCKET) x->handle, x->buffer, x->offset, x->size,\
216 x->socket_flags, &x->error);
219 async_invoke_io_thread (gpointer data)
223 thread = mono_thread_current ();
224 thread->threadpool_thread = TRUE;
225 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
228 MonoSocketAsyncResult *state;
231 state = (MonoSocketAsyncResult *) data;
233 InterlockedDecrement (&pending_io_items);
235 /* worker threads invokes methods in different domains,
236 * so we need to set the right domain here */
237 switch (state->operation) {
239 state->total = ICALL_RECV (state);
242 state->total = ICALL_SEND (state);
246 domain = ((MonoObject *)ar)->vtable->domain;
247 mono_thread_push_appdomain_ref (domain);
248 if (mono_domain_set (domain, FALSE)) {
251 mono_async_invoke (ar);
252 ac = (ASyncCall *) ar->object_data;
254 if (ac->msg->exc != NULL)
255 mono_unhandled_exception (ac->msg->exc);
257 mono_domain_set (mono_get_root_domain (), TRUE);
259 mono_thread_pop_appdomain_ref ();
260 InterlockedDecrement (&busy_io_worker_threads);
263 data = dequeue_job (&io_queue_lock, &async_io_queue);
268 guint32 start_time = GetTickCount ();
271 wr = WaitForSingleObjectEx (io_job_added, (guint32)timeout, TRUE);
272 if (THREAD_WANTS_A_BREAK (thread))
273 mono_thread_interruption_checkpoint ();
275 timeout -= GetTickCount () - start_time;
277 if (wr != WAIT_TIMEOUT)
278 data = dequeue_job (&io_queue_lock, &async_io_queue);
280 while (!data && timeout > 0);
284 if (InterlockedDecrement (&io_worker_threads) < 2) {
285 /* If we have pending items, keep the thread alive */
286 if (InterlockedCompareExchange (&pending_io_items, 0, 0) != 0) {
287 InterlockedIncrement (&io_worker_threads);
294 InterlockedIncrement (&busy_io_worker_threads);
297 g_assert_not_reached ();
301 start_io_thread_or_queue (MonoSocketAsyncResult *ares)
306 busy = (int) InterlockedCompareExchange (&busy_io_worker_threads, 0, -1);
307 worker = (int) InterlockedCompareExchange (&io_worker_threads, 0, -1);
308 if (worker <= ++busy &&
309 worker < mono_io_max_worker_threads) {
310 InterlockedIncrement (&busy_io_worker_threads);
311 InterlockedIncrement (&io_worker_threads);
312 domain = ((ares) ? ((MonoObject *) ares)->vtable->domain : mono_domain_get ());
313 mono_thread_create (mono_get_root_domain (), async_invoke_io_thread, ares);
315 append_job (&io_queue_lock, &async_io_queue, ares);
316 ReleaseSemaphore (io_job_added, 1, NULL);
321 process_io_event (GSList *list, int event)
323 MonoSocketAsyncResult *state;
329 state = (MonoSocketAsyncResult *) list->data;
330 if (get_event_from_state (state) == event)
337 oldlist = g_slist_remove_link (oldlist, list);
338 g_slist_free_1 (list);
340 g_print ("Dispatching event %d on socket %d\n", event, state->handle);
342 InterlockedIncrement (&pending_io_items);
343 start_io_thread_or_queue (state);
350 mark_bad_fds (mono_pollfd *pfds, int nfds)
356 for (i = 0; i < nfds; i++) {
361 ret = mono_poll (pfd, 1, 0);
362 if (ret == -1 && errno == EBADF) {
363 pfd->revents |= MONO_POLLNVAL;
365 } else if (ret == 1) {
374 socket_io_poll_main (gpointer p)
376 #define INITIAL_POLLFD_SIZE 1024
377 #define POLL_ERRORS (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL)
378 SocketIOData *data = p;
385 thread = mono_thread_current ();
386 thread->threadpool_thread = TRUE;
387 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
389 allocated = INITIAL_POLLFD_SIZE;
390 pfds = g_new0 (mono_pollfd, allocated);
391 INIT_POLLFD (pfds, data->pipe [0], MONO_POLLIN);
392 for (i = 1; i < allocated; i++)
393 INIT_POLLFD (&pfds [i], -1, 0);
403 if (THREAD_WANTS_A_BREAK (thread))
404 mono_thread_interruption_checkpoint ();
407 nsock = mono_poll (pfds, maxfd, -1);
408 } while (nsock == -1 && errno == EINTR);
411 * Apart from EINTR, we only check EBADF, for the rest:
412 * EINVAL: mono_poll() 'protects' us from descriptor
413 * numbers above the limit if using select() by marking
414 * then as MONO_POLLERR. If a system poll() is being
415 * used, the number of descriptor we're passing will not
416 * be over sysconf(_SC_OPEN_MAX), as the error would have
417 * happened when opening.
419 * EFAULT: we own the memory pointed by pfds.
420 * ENOMEM: we're doomed anyway
424 if (nsock == -1 && errno == EBADF) {
425 pfds->revents = 0; /* Just in case... */
426 nsock = mark_bad_fds (pfds, maxfd);
429 if ((pfds->revents & POLL_ERRORS) != 0) {
430 /* We're supposed to die now, as the pipe has been closed */
432 socket_io_cleanup (data);
436 /* Got a new socket */
437 if ((pfds->revents & MONO_POLLIN) != 0) {
440 for (i = 1; i < allocated; i++) {
442 if (pfd->fd == -1 || pfd->fd == data->newpfd->fd)
446 if (i == allocated) {
451 allocated = allocated * 2;
452 pfds = g_renew (mono_pollfd, oldfd, allocated);
454 for (; i < allocated; i++)
455 INIT_POLLFD (&pfds [i], -1, 0);
457 #ifndef PLATFORM_WIN32
458 nread = read (data->pipe [0], one, 1);
460 nread = recv ((SOCKET) data->pipe [0], one, 1, 0);
464 return; /* we're closed */
467 INIT_POLLFD (&pfds [i], data->newpfd->fd, data->newpfd->events);
468 ReleaseSemaphore (data->new_sem, 1, NULL);
477 EnterCriticalSection (&data->io_lock);
478 if (data->inited == 0) {
480 return; /* cleanup called */
483 for (i = 1; i < maxfd && nsock > 0; i++) {
485 if (pfd->fd == -1 || pfd->revents == 0)
489 list = g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
490 if (list != NULL && (pfd->revents & (MONO_POLLIN | POLL_ERRORS)) != 0) {
491 list = process_io_event (list, MONO_POLLIN);
494 if (list != NULL && (pfd->revents & (MONO_POLLOUT | POLL_ERRORS)) != 0) {
495 list = process_io_event (list, MONO_POLLOUT);
499 g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (pfd->fd), list);
500 pfd->events = get_events_from_list (list);
502 g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
508 LeaveCriticalSection (&data->io_lock);
513 #define EPOLL_ERRORS (EPOLLERR | EPOLLHUP)
515 socket_io_epoll_main (gpointer p)
520 struct epoll_event *events, *evt;
521 const int nevents = 512;
525 epollfd = data->epollfd;
526 thread = mono_thread_current ();
527 thread->threadpool_thread = TRUE;
528 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
529 events = g_new0 (struct epoll_event, nevents);
534 if (THREAD_WANTS_A_BREAK (thread))
535 mono_thread_interruption_checkpoint ();
538 g_print ("epoll_wait init\n");
540 ready = epoll_wait (epollfd, events, nevents, -1);
544 g_print ("epoll_wait end with %d ready sockets (%d %s).\n", ready, err, (err) ? g_strerror (err) : "");
548 } while (ready == -1 && errno == EINTR);
554 g_warning ("epoll_wait: %d %s\n", err, g_strerror (err));
560 EnterCriticalSection (&data->io_lock);
561 if (data->inited == 0) {
563 g_print ("data->inited == 0\n");
567 return; /* cleanup called */
570 for (i = 0; i < ready; i++) {
576 list = g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
578 g_print ("Event %d on %d list length: %d\n", evt->events, fd, g_slist_length (list));
580 if (list != NULL && (evt->events & (EPOLLIN | EPOLL_ERRORS)) != 0) {
581 list = process_io_event (list, MONO_POLLIN);
584 if (list != NULL && (evt->events & (EPOLLOUT | EPOLL_ERRORS)) != 0) {
585 list = process_io_event (list, MONO_POLLOUT);
589 g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (fd), list);
590 evt->events = get_events_from_list (list);
592 g_print ("MOD %d to %d\n", fd, evt->events);
594 if (epoll_ctl (epollfd, EPOLL_CTL_MOD, fd, evt)) {
595 if (epoll_ctl (epollfd, EPOLL_CTL_ADD, fd, evt) == -1) {
598 g_message ("epoll_ctl(MOD): %d %s fd: %d events: %d", err, g_strerror (err), fd, evt->events);
604 g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (fd));
606 g_print ("DEL %d\n", fd);
608 epoll_ctl (epollfd, EPOLL_CTL_DEL, fd, evt);
611 LeaveCriticalSection (&data->io_lock);
617 * select/poll wake up when a socket is closed, but epoll just removes
618 * the socket from its internal list without notification.
621 mono_thread_pool_remove_socket (int sock)
625 MonoSocketAsyncResult *state;
627 if (socket_io_data.epoll_disabled == TRUE || socket_io_data.inited == FALSE)
630 EnterCriticalSection (&socket_io_data.io_lock);
631 list = g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
633 g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
635 LeaveCriticalSection (&socket_io_data.io_lock);
638 state = (MonoSocketAsyncResult *) list->data;
639 if (state->operation == AIO_OP_RECEIVE)
640 state->operation = AIO_OP_RECV_JUST_CALLBACK;
641 else if (state->operation == AIO_OP_SEND)
642 state->operation = AIO_OP_SEND_JUST_CALLBACK;
644 next = g_slist_remove_link (list, list);
645 list = process_io_event (list, MONO_POLLIN);
647 process_io_event (list, MONO_POLLOUT);
654 #ifdef PLATFORM_WIN32
656 connect_hack (gpointer x)
658 struct sockaddr_in *addr = (struct sockaddr_in *) x;
661 while (connect ((SOCKET) socket_io_data.pipe [1], (SOCKADDR *) addr, sizeof (struct sockaddr_in))) {
664 g_warning ("Error initializing async. sockets %d.\n", WSAGetLastError ());
665 g_assert (WSAGetLastError ());
672 socket_io_init (SocketIOData *data)
674 #ifdef PLATFORM_WIN32
675 struct sockaddr_in server;
676 struct sockaddr_in client;
682 inited = InterlockedCompareExchange (&data->inited, -1, -1);
686 EnterCriticalSection (&data->io_lock);
687 inited = InterlockedCompareExchange (&data->inited, -1, -1);
689 LeaveCriticalSection (&data->io_lock);
694 data->epoll_disabled = (g_getenv ("MONO_DISABLE_AIO") != NULL);
695 if (FALSE == data->epoll_disabled) {
696 data->epollfd = epoll_create (256);
697 data->epoll_disabled = (data->epollfd == -1);
698 if (data->epoll_disabled && g_getenv ("MONO_DEBUG"))
699 g_message ("epoll_create() failed. Using plain poll().");
704 data->epoll_disabled = TRUE;
707 #ifndef PLATFORM_WIN32
708 if (data->epoll_disabled) {
709 if (pipe (data->pipe) != 0) {
719 srv = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
720 g_assert (srv != INVALID_SOCKET);
721 data->pipe [1] = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
722 g_assert (data->pipe [1] != INVALID_SOCKET);
724 server.sin_family = AF_INET;
725 server.sin_addr.s_addr = inet_addr ("127.0.0.1");
727 if (bind (srv, (SOCKADDR *) &server, sizeof (server))) {
728 g_print ("%d\n", WSAGetLastError ());
732 len = sizeof (server);
733 getsockname (srv, (SOCKADDR *) &server, &len);
735 mono_thread_create (mono_get_root_domain (), connect_hack, &server);
736 len = sizeof (server);
737 data->pipe [0] = accept (srv, (SOCKADDR *) &client, &len);
738 g_assert (data->pipe [0] != INVALID_SOCKET);
741 mono_io_max_worker_threads = mono_max_worker_threads / 2;
742 if (mono_io_max_worker_threads < 10)
743 mono_io_max_worker_threads = 10;
745 data->sock_to_state = g_hash_table_new (g_direct_hash, g_direct_equal);
747 if (data->epoll_disabled)
748 data->new_sem = CreateSemaphore (NULL, 1, 1, NULL);
749 io_job_added = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
750 InitializeCriticalSection (&io_queue_lock);
751 if (data->epoll_disabled) {
752 mono_thread_create (mono_get_root_domain (), socket_io_poll_main, data);
756 mono_thread_create (mono_get_root_domain (), socket_io_epoll_main, data);
759 InterlockedCompareExchange (&data->inited, 1, 0);
760 LeaveCriticalSection (&data->io_lock);
764 socket_io_add_poll (MonoSocketAsyncResult *state)
769 SocketIOData *data = &socket_io_data;
771 #if defined(PLATFORM_MACOSX) || defined(PLATFORM_BSD6) || defined(PLATFORM_WIN32)
772 /* select() for connect() does not work well on the Mac. Bug #75436. */
773 /* Bug #77637 for the BSD 6 case */
774 /* Bug #78888 for the Windows case */
775 if (state->operation == AIO_OP_CONNECT && state->blocking == TRUE) {
776 start_io_thread_or_queue (state);
780 WaitForSingleObject (data->new_sem, INFINITE);
781 if (data->newpfd == NULL)
782 data->newpfd = g_new0 (mono_pollfd, 1);
784 EnterCriticalSection (&data->io_lock);
785 list = g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (state->handle));
787 list = g_slist_alloc ();
790 list = g_slist_append (list, state);
793 events = get_events_from_list (list);
794 INIT_POLLFD (data->newpfd, GPOINTER_TO_INT (state->handle), events);
795 g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (state->handle), list);
796 LeaveCriticalSection (&data->io_lock);
797 *msg = (char) state->operation;
798 #ifndef PLATFORM_WIN32
799 write (data->pipe [1], msg, 1);
801 send ((SOCKET) data->pipe [1], msg, 1, 0);
807 socket_io_add_epoll (MonoSocketAsyncResult *state)
810 SocketIOData *data = &socket_io_data;
811 struct epoll_event event;
815 memset (&event, 0, sizeof (struct epoll_event));
816 fd = GPOINTER_TO_INT (state->handle);
817 EnterCriticalSection (&data->io_lock);
818 list = g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
820 list = g_slist_alloc ();
822 epoll_op = EPOLL_CTL_ADD;
824 list = g_slist_append (list, state);
825 epoll_op = EPOLL_CTL_MOD;
828 ievt = get_events_from_list (list);
829 if ((ievt & MONO_POLLIN) != 0)
830 event.events |= EPOLLIN;
831 if ((ievt & MONO_POLLOUT) != 0)
832 event.events |= EPOLLOUT;
834 g_hash_table_replace (data->sock_to_state, state->handle, list);
837 g_print ("%s %d with %d\n", epoll_op == EPOLL_CTL_ADD ? "ADD" : "MOD", fd, event.events);
839 if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
841 if (epoll_op == EPOLL_CTL_ADD && err == EEXIST) {
842 epoll_op = EPOLL_CTL_MOD;
843 if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
844 g_message ("epoll_ctl(MOD): %d %s\n", err, g_strerror (err));
849 LeaveCriticalSection (&data->io_lock);
855 socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
857 socket_io_init (&socket_io_data);
858 MONO_OBJECT_SETREF (state, ares, ares);
860 if (socket_io_data.epoll_disabled == FALSE) {
861 if (socket_io_add_epoll (state))
865 socket_io_add_poll (state);
869 socket_io_filter (MonoObject *target, MonoObject *state)
872 MonoSocketAsyncResult *sock_res = (MonoSocketAsyncResult *) state;
875 if (target == NULL || state == NULL)
878 if (socket_async_call_klass == NULL) {
879 klass = target->vtable->klass;
880 /* Check if it's SocketAsyncCall in System
881 * FIXME: check the assembly is signed correctly for extra care
883 if (klass->name [0] == 'S' && strcmp (klass->name, "SocketAsyncCall") == 0
884 && strcmp (mono_image_get_name (klass->image), "System") == 0
885 && klass->nested_in && strcmp (klass->nested_in->name, "Socket") == 0)
886 socket_async_call_klass = klass;
889 /* return both when socket_async_call_klass has not been seen yet and when
890 * the object is not an instance of the class.
892 if (target->vtable->klass != socket_async_call_klass)
895 op = sock_res->operation;
896 if (op < AIO_OP_FIRST || op >= AIO_OP_LAST)
903 mono_async_invoke (MonoAsyncResult *ares)
905 ASyncCall *ac = (ASyncCall *)ares->object_data;
906 MonoThread *thread = NULL;
908 if (ares->execution_context) {
909 /* use captured ExecutionContext (if available) */
910 thread = mono_thread_current ();
911 MONO_OBJECT_SETREF (ares, original_context, thread->execution_context);
912 MONO_OBJECT_SETREF (thread, execution_context, ares->execution_context);
914 ares->original_context = NULL;
918 ac->res = mono_message_invoke (ares->async_delegate, ac->msg,
919 &ac->msg->exc, &ac->out_args);
923 /* call async callback if cb_method != null*/
925 MonoObject *exc = NULL;
927 mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &exc);
928 /* 'exc' will be the previous ac->msg->exc if not NULL and not
929 * catched. If catched, this will be set to NULL and the
930 * exception will not be printed. */
931 MONO_OBJECT_SETREF (ac->msg, exc, exc);
934 /* restore original thread execution context if flow isn't suppressed, i.e. non null */
935 if (ares->original_context) {
936 MONO_OBJECT_SETREF (thread, execution_context, ares->original_context);
937 ares->original_context = NULL;
940 /* notify listeners */
941 mono_monitor_enter ((MonoObject *) ares);
942 if (ares->handle != NULL) {
943 ac->wait_event = (gsize)((MonoWaitHandle *) ares->handle)->handle;
944 SetEvent ((gpointer)(gsize)ac->wait_event);
946 mono_monitor_exit ((MonoObject *) ares);
948 EnterCriticalSection (&ares_lock);
949 mono_g_hash_table_remove (ares_htable, ares);
950 LeaveCriticalSection (&ares_lock);
954 mono_thread_pool_init ()
957 int threads_per_cpu = THREADS_PER_CPU;
959 if ((int) InterlockedCompareExchange (&tp_inited, 1, 0) == 1)
962 MONO_GC_REGISTER_ROOT (ares_htable);
963 InitializeCriticalSection (&socket_io_data.io_lock);
964 InitializeCriticalSection (&ares_lock);
965 ares_htable = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_VALUE_GC);
966 job_added = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
967 GetSystemInfo (&info);
968 if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
969 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
970 if (threads_per_cpu <= 0)
971 threads_per_cpu = THREADS_PER_CPU;
974 mono_max_worker_threads = 20 + threads_per_cpu * info.dwNumberOfProcessors;
976 async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
977 g_assert (async_call_klass);
981 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
984 MonoDomain *domain = mono_domain_get ();
985 MonoAsyncResult *ares;
989 ac = GC_MALLOC (sizeof (ASyncCall));
990 #elif defined(HAVE_SGEN_GC)
991 ac = mono_object_new (mono_domain_get (), async_call_klass);
993 /* We'll leak the event if creaated... */
994 ac = g_new0 (ASyncCall, 1);
997 MONO_OBJECT_SETREF (ac, msg, msg);
998 MONO_OBJECT_SETREF (ac, state, state);
1000 if (async_callback) {
1001 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
1002 ac->cb_target = async_callback;
1005 ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
1006 MONO_OBJECT_SETREF (ares, async_delegate, target);
1008 EnterCriticalSection (&ares_lock);
1009 mono_g_hash_table_insert (ares_htable, ares, ares);
1010 LeaveCriticalSection (&ares_lock);
1012 if (socket_io_filter (target, state)) {
1013 socket_io_add (ares, (MonoSocketAsyncResult *) state);
1017 start_thread_or_queue (ares);
1022 start_thread_or_queue (MonoAsyncResult *ares)
1027 busy = (int) InterlockedCompareExchange (&busy_worker_threads, 0, -1);
1028 worker = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1029 if (worker <= ++busy &&
1030 worker < mono_max_worker_threads) {
1031 InterlockedIncrement (&mono_worker_threads);
1032 InterlockedIncrement (&busy_worker_threads);
1033 domain = ((MonoObject *) ares)->vtable->domain;
1034 mono_thread_create (mono_get_root_domain (), async_invoke_thread, ares);
1036 append_job (&mono_delegate_section, &async_call_queue, ares);
1037 ReleaseSemaphore (job_added, 1, NULL);
1042 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1049 /* check if already finished */
1050 mono_monitor_enter ((MonoObject *) ares);
1052 if (ares->endinvoke_called) {
1053 *exc = (MonoObject *)mono_exception_from_name (mono_defaults.corlib, "System",
1054 "InvalidOperationException");
1055 mono_monitor_exit ((MonoObject *) ares);
1059 ares->endinvoke_called = 1;
1060 ac = (ASyncCall *)ares->object_data;
1062 g_assert (ac != NULL);
1064 /* wait until we are really finished */
1065 if (!ares->completed) {
1066 if (ares->handle == NULL) {
1067 ac->wait_event = (gsize)CreateEvent (NULL, TRUE, FALSE, NULL);
1068 MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), (gpointer)(gsize)ac->wait_event));
1070 mono_monitor_exit ((MonoObject *) ares);
1071 WaitForSingleObjectEx ((gpointer)(gsize)ac->wait_event, INFINITE, TRUE);
1073 mono_monitor_exit ((MonoObject *) ares);
1076 *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1077 *out_args = ac->out_args;
1083 mono_thread_pool_cleanup (void)
1087 EnterCriticalSection (&mono_delegate_section);
1088 g_list_free (async_call_queue);
1089 async_call_queue = NULL;
1090 release = (gint) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1091 LeaveCriticalSection (&mono_delegate_section);
1093 ReleaseSemaphore (job_added, release, NULL);
1095 socket_io_cleanup (&socket_io_data);
1099 append_job (CRITICAL_SECTION *cs, GList **plist, gpointer ar)
1103 EnterCriticalSection (cs);
1106 list = g_list_append (list, ar);
1108 for (tmp = list; tmp && tmp->data != NULL; tmp = tmp->next);
1110 list = g_list_append (list, ar);
1116 LeaveCriticalSection (cs);
1120 dequeue_job (CRITICAL_SECTION *cs, GList **plist)
1123 GList *tmp, *tmp2, *list;
1125 EnterCriticalSection (cs);
1132 for (tmp2 = tmp; tmp2->next != NULL; tmp2 = tmp2->next);
1141 LeaveCriticalSection (cs);
1147 async_invoke_thread (gpointer data)
1153 thread = mono_thread_current ();
1154 thread->threadpool_thread = TRUE;
1155 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
1158 MonoAsyncResult *ar;
1160 ar = (MonoAsyncResult *) data;
1162 /* worker threads invokes methods in different domains,
1163 * so we need to set the right domain here */
1164 domain = ((MonoObject *)ar)->vtable->domain;
1165 mono_thread_push_appdomain_ref (domain);
1166 if (mono_domain_set (domain, FALSE)) {
1169 mono_async_invoke (ar);
1170 ac = (ASyncCall *) ar->object_data;
1172 if (ac->msg->exc != NULL)
1173 mono_unhandled_exception (ac->msg->exc);
1175 mono_domain_set (mono_get_root_domain (), TRUE);
1177 mono_thread_pop_appdomain_ref ();
1178 InterlockedDecrement (&busy_worker_threads);
1181 data = dequeue_job (&mono_delegate_section, &async_call_queue);
1185 int timeout = 10000;
1186 guint32 start_time = GetTickCount ();
1189 wr = WaitForSingleObjectEx (job_added, (guint32)timeout, TRUE);
1190 if (THREAD_WANTS_A_BREAK (thread))
1191 mono_thread_interruption_checkpoint ();
1193 timeout -= GetTickCount () - start_time;
1195 if (wr != WAIT_TIMEOUT)
1196 data = dequeue_job (&mono_delegate_section, &async_call_queue);
1198 while (!data && timeout > 0);
1202 workers = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1203 min = (int) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
1205 while (!data && workers <= min) {
1206 WaitForSingleObjectEx (job_added, INFINITE, TRUE);
1207 if (THREAD_WANTS_A_BREAK (thread))
1208 mono_thread_interruption_checkpoint ();
1210 data = dequeue_job (&mono_delegate_section, &async_call_queue);
1211 workers = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1212 min = (int) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
1217 InterlockedDecrement (&mono_worker_threads);
1221 InterlockedIncrement (&busy_worker_threads);
1224 g_assert_not_reached ();
1228 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
1232 MONO_ARCH_SAVE_REGS;
1234 busy = (gint) InterlockedCompareExchange (&busy_worker_threads, 0, -1);
1235 *workerThreads = mono_max_worker_threads - busy;
1236 *completionPortThreads = 0;
1240 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
1242 MONO_ARCH_SAVE_REGS;
1244 *workerThreads = mono_max_worker_threads;
1245 *completionPortThreads = 0;
1249 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
1253 MONO_ARCH_SAVE_REGS;
1255 workers = (gint) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
1256 *workerThreads = workers;
1257 *completionPortThreads = 0;
1261 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
1263 MONO_ARCH_SAVE_REGS;
1265 if (workerThreads < 0 || workerThreads > mono_max_worker_threads)
1267 InterlockedExchange (&mono_min_worker_threads, workerThreads);
1268 /* FIXME: should actually start the idle threads if needed */