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;
99 MonoMethodMessage *msg;
101 MonoMethod *cb_method;
102 MonoDelegate *cb_target;
108 static void async_invoke_thread (gpointer data);
109 static void append_job (CRITICAL_SECTION *cs, GList **plist, gpointer ar);
110 static void start_thread_or_queue (MonoAsyncResult *ares);
111 static void mono_async_invoke (MonoAsyncResult *ares);
112 static gpointer dequeue_job (CRITICAL_SECTION *cs, GList **plist);
114 static GList *async_call_queue = NULL;
115 static GList *async_io_queue = NULL;
117 static MonoClass *socket_async_call_klass;
119 #define INIT_POLLFD(a, b, c) {(a)->fd = b; (a)->events = c; (a)->revents = 0;}
128 AIO_OP_RECV_JUST_CALLBACK,
129 AIO_OP_SEND_JUST_CALLBACK,
134 socket_io_cleanup (SocketIOData *data)
138 if (data->inited == 0)
141 EnterCriticalSection (&data->io_lock);
143 #ifdef PLATFORM_WIN32
144 closesocket (data->pipe [0]);
145 closesocket (data->pipe [1]);
147 close (data->pipe [0]);
148 close (data->pipe [1]);
153 CloseHandle (data->new_sem);
154 data->new_sem = NULL;
155 g_hash_table_destroy (data->sock_to_state);
156 data->sock_to_state = NULL;
157 g_list_free (async_io_queue);
158 async_io_queue = NULL;
159 release = (gint) InterlockedCompareExchange (&io_worker_threads, 0, -1);
161 ReleaseSemaphore (io_job_added, release, NULL);
162 g_free (data->newpfd);
165 if (FALSE == data->epoll_disabled)
166 close (data->epollfd);
168 LeaveCriticalSection (&data->io_lock);
172 get_event_from_state (MonoSocketAsyncResult *state)
174 switch (state->operation) {
177 case AIO_OP_RECV_JUST_CALLBACK:
178 case AIO_OP_RECEIVEFROM:
181 case AIO_OP_SEND_JUST_CALLBACK:
185 default: /* Should never happen */
186 g_print ("get_event_from_state: unknown value in switch!!!\n");
192 get_events_from_list (GSList *list)
194 MonoSocketAsyncResult *state;
197 while (list && list->data) {
198 state = (MonoSocketAsyncResult *) list->data;
199 events |= get_event_from_state (state);
206 #define ICALL_RECV(x) ves_icall_System_Net_Sockets_Socket_Receive_internal (\
207 (SOCKET) x->handle, x->buffer, x->offset, x->size,\
208 x->socket_flags, &x->error);
210 #define ICALL_SEND(x) ves_icall_System_Net_Sockets_Socket_Send_internal (\
211 (SOCKET) x->handle, x->buffer, x->offset, x->size,\
212 x->socket_flags, &x->error);
215 async_invoke_io_thread (gpointer data)
219 thread = mono_thread_current ();
220 thread->threadpool_thread = TRUE;
221 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
224 MonoSocketAsyncResult *state;
227 state = (MonoSocketAsyncResult *) data;
229 InterlockedDecrement (&pending_io_items);
231 /* worker threads invokes methods in different domains,
232 * so we need to set the right domain here */
233 switch (state->operation) {
235 state->total = ICALL_RECV (state);
238 state->total = ICALL_SEND (state);
242 domain = ((MonoObject *)ar)->vtable->domain;
243 mono_thread_push_appdomain_ref (domain);
244 if (mono_domain_set (domain, FALSE)) {
247 mono_async_invoke (ar);
248 ac = (ASyncCall *) ar->data;
250 if (ac->msg->exc != NULL)
251 mono_unhandled_exception (ac->msg->exc);
253 mono_domain_set (mono_get_root_domain (), TRUE);
255 mono_thread_pop_appdomain_ref ();
256 InterlockedDecrement (&busy_io_worker_threads);
259 data = dequeue_job (&io_queue_lock, &async_io_queue);
264 guint32 start_time = GetTickCount ();
267 wr = WaitForSingleObjectEx (io_job_added, (guint32)timeout, TRUE);
268 if (THREAD_WANTS_A_BREAK (thread))
269 mono_thread_interruption_checkpoint ();
271 timeout -= GetTickCount () - start_time;
273 if (wr != WAIT_TIMEOUT)
274 data = dequeue_job (&io_queue_lock, &async_io_queue);
276 while (!data && timeout > 0);
280 if (InterlockedDecrement (&io_worker_threads) < 2) {
281 /* If we have pending items, keep the thread alive */
282 if (InterlockedCompareExchange (&pending_io_items, 0, 0) != 0) {
283 InterlockedIncrement (&io_worker_threads);
290 InterlockedIncrement (&busy_io_worker_threads);
293 g_assert_not_reached ();
297 start_io_thread_or_queue (MonoSocketAsyncResult *ares)
302 busy = (int) InterlockedCompareExchange (&busy_io_worker_threads, 0, -1);
303 worker = (int) InterlockedCompareExchange (&io_worker_threads, 0, -1);
304 if (worker <= ++busy &&
305 worker < mono_io_max_worker_threads) {
306 InterlockedIncrement (&busy_io_worker_threads);
307 InterlockedIncrement (&io_worker_threads);
308 domain = ((ares) ? ((MonoObject *) ares)->vtable->domain : mono_domain_get ());
309 mono_thread_create (mono_get_root_domain (), async_invoke_io_thread, ares);
311 append_job (&io_queue_lock, &async_io_queue, ares);
312 ReleaseSemaphore (io_job_added, 1, NULL);
317 process_io_event (GSList *list, int event)
319 MonoSocketAsyncResult *state;
325 state = (MonoSocketAsyncResult *) list->data;
326 if (get_event_from_state (state) == event)
333 oldlist = g_slist_remove_link (oldlist, list);
334 g_slist_free_1 (list);
336 g_print ("Dispatching event %d on socket %d\n", event, state->handle);
338 InterlockedIncrement (&pending_io_items);
339 start_io_thread_or_queue (state);
346 mark_bad_fds (mono_pollfd *pfds, int nfds)
352 for (i = 0; i < nfds; i++) {
357 ret = mono_poll (pfd, 1, 0);
358 if (ret == -1 && errno == EBADF) {
359 pfd->revents |= MONO_POLLNVAL;
361 } else if (ret == 1) {
370 socket_io_poll_main (gpointer p)
372 #define INITIAL_POLLFD_SIZE 1024
373 #define POLL_ERRORS (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL)
374 SocketIOData *data = p;
381 thread = mono_thread_current ();
382 thread->threadpool_thread = TRUE;
383 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
385 allocated = INITIAL_POLLFD_SIZE;
386 pfds = g_new0 (mono_pollfd, allocated);
387 INIT_POLLFD (pfds, data->pipe [0], MONO_POLLIN);
388 for (i = 1; i < allocated; i++)
389 INIT_POLLFD (&pfds [i], -1, 0);
399 if (THREAD_WANTS_A_BREAK (thread))
400 mono_thread_interruption_checkpoint ();
403 nsock = mono_poll (pfds, maxfd, -1);
404 } while (nsock == -1 && errno == EINTR);
407 * Apart from EINTR, we only check EBADF, for the rest:
408 * EINVAL: mono_poll() 'protects' us from descriptor
409 * numbers above the limit if using select() by marking
410 * then as MONO_POLLERR. If a system poll() is being
411 * used, the number of descriptor we're passing will not
412 * be over sysconf(_SC_OPEN_MAX), as the error would have
413 * happened when opening.
415 * EFAULT: we own the memory pointed by pfds.
416 * ENOMEM: we're doomed anyway
420 if (nsock == -1 && errno == EBADF) {
421 pfds->revents = 0; /* Just in case... */
422 nsock = mark_bad_fds (pfds, maxfd);
425 if ((pfds->revents & POLL_ERRORS) != 0) {
426 /* We're supposed to die now, as the pipe has been closed */
428 socket_io_cleanup (data);
432 /* Got a new socket */
433 if ((pfds->revents & MONO_POLLIN) != 0) {
436 for (i = 1; i < allocated; i++) {
438 if (pfd->fd == -1 || pfd->fd == data->newpfd->fd)
442 if (i == allocated) {
447 allocated = allocated * 2;
448 pfds = g_renew (mono_pollfd, oldfd, allocated);
450 for (; i < allocated; i++)
451 INIT_POLLFD (&pfds [i], -1, 0);
453 #ifndef PLATFORM_WIN32
454 nread = read (data->pipe [0], one, 1);
456 nread = recv ((SOCKET) data->pipe [0], one, 1, 0);
460 return; /* we're closed */
463 INIT_POLLFD (&pfds [i], data->newpfd->fd, data->newpfd->events);
464 ReleaseSemaphore (data->new_sem, 1, NULL);
473 EnterCriticalSection (&data->io_lock);
474 if (data->inited == 0) {
476 return; /* cleanup called */
479 for (i = 1; i < maxfd && nsock > 0; i++) {
481 if (pfd->fd == -1 || pfd->revents == 0)
485 list = g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
486 if (list != NULL && (pfd->revents & (MONO_POLLIN | POLL_ERRORS)) != 0) {
487 list = process_io_event (list, MONO_POLLIN);
490 if (list != NULL && (pfd->revents & (MONO_POLLOUT | POLL_ERRORS)) != 0) {
491 list = process_io_event (list, MONO_POLLOUT);
495 g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (pfd->fd), list);
496 pfd->events = get_events_from_list (list);
498 g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
504 LeaveCriticalSection (&data->io_lock);
509 #define EPOLL_ERRORS (EPOLLERR | EPOLLHUP)
511 socket_io_epoll_main (gpointer p)
516 struct epoll_event *events, *evt;
517 const int nevents = 512;
521 epollfd = data->epollfd;
522 thread = mono_thread_current ();
523 thread->threadpool_thread = TRUE;
524 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
525 events = g_new0 (struct epoll_event, nevents);
530 if (THREAD_WANTS_A_BREAK (thread))
531 mono_thread_interruption_checkpoint ();
534 g_print ("epoll_wait init\n");
536 ready = epoll_wait (epollfd, events, nevents, -1);
540 g_print ("epoll_wait end with %d ready sockets (%d %s).\n", ready, err, (err) ? g_strerror (err) : "");
544 } while (ready == -1 && errno == EINTR);
550 g_warning ("epoll_wait: %d %s\n", err, g_strerror (err));
556 EnterCriticalSection (&data->io_lock);
557 if (data->inited == 0) {
559 g_print ("data->inited == 0\n");
563 return; /* cleanup called */
566 for (i = 0; i < ready; i++) {
572 list = g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
574 g_print ("Event %d on %d list length: %d\n", evt->events, fd, g_slist_length (list));
576 if (list != NULL && (evt->events & (EPOLLIN | EPOLL_ERRORS)) != 0) {
577 list = process_io_event (list, MONO_POLLIN);
580 if (list != NULL && (evt->events & (EPOLLOUT | EPOLL_ERRORS)) != 0) {
581 list = process_io_event (list, MONO_POLLOUT);
585 g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (fd), list);
586 evt->events = get_events_from_list (list);
588 g_print ("MOD %d to %d\n", fd, evt->events);
590 if (epoll_ctl (epollfd, EPOLL_CTL_MOD, fd, evt)) {
591 if (epoll_ctl (epollfd, EPOLL_CTL_ADD, fd, evt) == -1) {
594 g_message ("epoll_ctl(MOD): %d %s fd: %d events: %d", err, g_strerror (err), fd, evt->events);
600 g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (fd));
602 g_print ("DEL %d\n", fd);
604 epoll_ctl (epollfd, EPOLL_CTL_DEL, fd, evt);
607 LeaveCriticalSection (&data->io_lock);
613 * select/poll wake up when a socket is closed, but epoll just removes
614 * the socket from its internal list without notification.
617 mono_thread_pool_remove_socket (int sock)
621 MonoSocketAsyncResult *state;
623 if (socket_io_data.epoll_disabled == TRUE || socket_io_data.inited == FALSE)
626 EnterCriticalSection (&socket_io_data.io_lock);
627 list = g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
629 g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
631 LeaveCriticalSection (&socket_io_data.io_lock);
634 state = (MonoSocketAsyncResult *) list->data;
635 if (state->operation == AIO_OP_RECEIVE)
636 state->operation = AIO_OP_RECV_JUST_CALLBACK;
637 else if (state->operation == AIO_OP_SEND)
638 state->operation = AIO_OP_SEND_JUST_CALLBACK;
640 next = g_slist_remove_link (list, list);
641 list = process_io_event (list, MONO_POLLIN);
643 process_io_event (list, MONO_POLLOUT);
650 #ifdef PLATFORM_WIN32
652 connect_hack (gpointer x)
654 struct sockaddr_in *addr = (struct sockaddr_in *) x;
657 while (connect ((SOCKET) socket_io_data.pipe [1], (SOCKADDR *) addr, sizeof (struct sockaddr_in))) {
660 g_warning ("Error initializing async. sockets %d.\n", WSAGetLastError ());
661 g_assert (WSAGetLastError ());
668 socket_io_init (SocketIOData *data)
670 #ifdef PLATFORM_WIN32
671 struct sockaddr_in server;
672 struct sockaddr_in client;
678 inited = InterlockedCompareExchange (&data->inited, -1, -1);
682 EnterCriticalSection (&data->io_lock);
683 inited = InterlockedCompareExchange (&data->inited, -1, -1);
685 LeaveCriticalSection (&data->io_lock);
690 data->epoll_disabled = (g_getenv ("MONO_DISABLE_AIO") != NULL);
691 if (FALSE == data->epoll_disabled) {
692 data->epollfd = epoll_create (256);
693 data->epoll_disabled = (data->epollfd == -1);
694 if (data->epoll_disabled && g_getenv ("MONO_DEBUG"))
695 g_message ("epoll_create() failed. Using plain poll().");
700 data->epoll_disabled = TRUE;
703 #ifndef PLATFORM_WIN32
704 if (data->epoll_disabled) {
705 if (pipe (data->pipe) != 0) {
715 srv = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
716 g_assert (srv != INVALID_SOCKET);
717 data->pipe [1] = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
718 g_assert (data->pipe [1] != INVALID_SOCKET);
720 server.sin_family = AF_INET;
721 server.sin_addr.s_addr = inet_addr ("127.0.0.1");
723 if (bind (srv, (SOCKADDR *) &server, sizeof (server))) {
724 g_print ("%d\n", WSAGetLastError ());
728 len = sizeof (server);
729 getsockname (srv, (SOCKADDR *) &server, &len);
731 mono_thread_create (mono_get_root_domain (), connect_hack, &server);
732 len = sizeof (server);
733 data->pipe [0] = accept (srv, (SOCKADDR *) &client, &len);
734 g_assert (data->pipe [0] != INVALID_SOCKET);
737 mono_io_max_worker_threads = mono_max_worker_threads / 2;
738 if (mono_io_max_worker_threads < 10)
739 mono_io_max_worker_threads = 10;
741 data->sock_to_state = g_hash_table_new (g_direct_hash, g_direct_equal);
743 if (data->epoll_disabled)
744 data->new_sem = CreateSemaphore (NULL, 1, 1, NULL);
745 io_job_added = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
746 InitializeCriticalSection (&io_queue_lock);
747 if (data->epoll_disabled) {
748 mono_thread_create (mono_get_root_domain (), socket_io_poll_main, data);
752 mono_thread_create (mono_get_root_domain (), socket_io_epoll_main, data);
755 InterlockedCompareExchange (&data->inited, 1, 0);
756 LeaveCriticalSection (&data->io_lock);
760 socket_io_add_poll (MonoSocketAsyncResult *state)
765 SocketIOData *data = &socket_io_data;
767 #if defined(PLATFORM_MACOSX) || defined(PLATFORM_BSD6)
768 /* select() for connect() does not work well on the Mac. Bug #75436. */
769 /* Bug #77637 for the BSD 6 case */
770 if (state->operation == AIO_OP_CONNECT && state->blocking == TRUE) {
771 start_io_thread_or_queue (state);
775 WaitForSingleObject (data->new_sem, INFINITE);
776 if (data->newpfd == NULL)
777 data->newpfd = g_new0 (mono_pollfd, 1);
779 EnterCriticalSection (&data->io_lock);
780 list = g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (state->handle));
782 list = g_slist_alloc ();
785 list = g_slist_append (list, state);
788 events = get_events_from_list (list);
789 INIT_POLLFD (data->newpfd, GPOINTER_TO_INT (state->handle), events);
790 g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (state->handle), list);
791 LeaveCriticalSection (&data->io_lock);
792 *msg = (char) state->operation;
793 #ifndef PLATFORM_WIN32
794 write (data->pipe [1], msg, 1);
796 send ((SOCKET) data->pipe [1], msg, 1, 0);
802 socket_io_add_epoll (MonoSocketAsyncResult *state)
805 SocketIOData *data = &socket_io_data;
806 struct epoll_event event;
810 memset (&event, 0, sizeof (struct epoll_event));
811 fd = GPOINTER_TO_INT (state->handle);
812 EnterCriticalSection (&data->io_lock);
813 list = g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
815 list = g_slist_alloc ();
817 epoll_op = EPOLL_CTL_ADD;
819 list = g_slist_append (list, state);
820 epoll_op = EPOLL_CTL_MOD;
823 ievt = get_events_from_list (list);
824 if ((ievt & MONO_POLLIN) != 0)
825 event.events |= EPOLLIN;
826 if ((ievt & MONO_POLLOUT) != 0)
827 event.events |= EPOLLOUT;
829 g_hash_table_replace (data->sock_to_state, state->handle, list);
832 g_print ("%s %d with %d\n", epoll_op == EPOLL_CTL_ADD ? "ADD" : "MOD", fd, event.events);
834 if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
836 if (epoll_op == EPOLL_CTL_ADD && err == EEXIST) {
837 epoll_op = EPOLL_CTL_MOD;
838 if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
839 g_message ("epoll_ctl(MOD): %d %s\n", err, g_strerror (err));
844 LeaveCriticalSection (&data->io_lock);
850 socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
852 socket_io_init (&socket_io_data);
853 MONO_OBJECT_SETREF (state, ares, ares);
855 if (socket_io_data.epoll_disabled == FALSE) {
856 if (socket_io_add_epoll (state))
860 socket_io_add_poll (state);
864 socket_io_filter (MonoObject *target, MonoObject *state)
867 MonoSocketAsyncResult *sock_res = (MonoSocketAsyncResult *) state;
870 if (target == NULL || state == NULL)
873 if (socket_async_call_klass == NULL) {
874 klass = target->vtable->klass;
875 /* Check if it's SocketAsyncCall in System
876 * FIXME: check the assembly is signed correctly for extra care
878 if (klass->name [0] == 'S' && strcmp (klass->name, "SocketAsyncCall") == 0
879 && strcmp (mono_image_get_name (klass->image), "System") == 0
880 && klass->nested_in && strcmp (klass->nested_in->name, "Socket") == 0)
881 socket_async_call_klass = klass;
884 /* return both when socket_async_call_klass has not been seen yet and when
885 * the object is not an instance of the class.
887 if (target->vtable->klass != socket_async_call_klass)
890 op = sock_res->operation;
891 if (op < AIO_OP_FIRST || op >= AIO_OP_LAST)
898 mono_async_invoke (MonoAsyncResult *ares)
900 ASyncCall *ac = (ASyncCall *)ares->data;
901 MonoThread *thread = NULL;
903 if (ares->execution_context) {
904 /* use captured ExecutionContext (if available) */
905 thread = mono_thread_current ();
906 MONO_OBJECT_SETREF (ares, original_context, thread->execution_context);
907 MONO_OBJECT_SETREF (thread, execution_context, ares->execution_context);
909 ares->original_context = NULL;
913 ac->res = mono_message_invoke (ares->async_delegate, ac->msg,
914 &ac->msg->exc, &ac->out_args);
918 /* call async callback if cb_method != null*/
920 MonoObject *exc = NULL;
922 mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &exc);
923 /* 'exc' will be the previous ac->msg->exc if not NULL and not
924 * catched. If catched, this will be set to NULL and the
925 * exception will not be printed. */
926 MONO_OBJECT_SETREF (ac->msg, exc, exc);
929 /* restore original thread execution context if flow isn't suppressed, i.e. non null */
930 if (ares->original_context) {
931 MONO_OBJECT_SETREF (thread, execution_context, ares->original_context);
932 ares->original_context = NULL;
935 /* notify listeners */
936 mono_monitor_enter ((MonoObject *) ares);
937 if (ares->handle != NULL) {
938 ac->wait_event = ((MonoWaitHandle *) ares->handle)->handle;
939 SetEvent (ac->wait_event);
941 mono_monitor_exit ((MonoObject *) ares);
943 EnterCriticalSection (&ares_lock);
944 mono_g_hash_table_remove (ares_htable, ares);
945 LeaveCriticalSection (&ares_lock);
949 mono_thread_pool_init ()
952 int threads_per_cpu = THREADS_PER_CPU;
954 if ((int) InterlockedCompareExchange (&tp_inited, 1, 0) == 1)
957 MONO_GC_REGISTER_ROOT (ares_htable);
958 InitializeCriticalSection (&socket_io_data.io_lock);
959 InitializeCriticalSection (&ares_lock);
960 ares_htable = mono_g_hash_table_new (NULL, NULL);
961 job_added = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
962 GetSystemInfo (&info);
963 if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
964 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
965 if (threads_per_cpu <= 0)
966 threads_per_cpu = THREADS_PER_CPU;
969 mono_max_worker_threads = 20 + threads_per_cpu * info.dwNumberOfProcessors;
973 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
976 MonoDomain *domain = mono_domain_get ();
977 MonoAsyncResult *ares;
981 ac = GC_MALLOC (sizeof (ASyncCall));
983 /* We'll leak the event if creaated... */
984 ac = g_new0 (ASyncCall, 1);
986 ac->wait_event = NULL;
990 if (async_callback) {
991 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
992 ac->cb_target = async_callback;
995 ares = mono_async_result_new (domain, NULL, ac->state, ac);
996 MONO_OBJECT_SETREF (ares, async_delegate, target);
998 EnterCriticalSection (&ares_lock);
999 mono_g_hash_table_insert (ares_htable, ares, ares);
1000 LeaveCriticalSection (&ares_lock);
1002 if (socket_io_filter (target, state)) {
1003 socket_io_add (ares, (MonoSocketAsyncResult *) state);
1007 start_thread_or_queue (ares);
1012 start_thread_or_queue (MonoAsyncResult *ares)
1017 busy = (int) InterlockedCompareExchange (&busy_worker_threads, 0, -1);
1018 worker = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1019 if (worker <= ++busy &&
1020 worker < mono_max_worker_threads) {
1021 InterlockedIncrement (&mono_worker_threads);
1022 InterlockedIncrement (&busy_worker_threads);
1023 domain = ((MonoObject *) ares)->vtable->domain;
1024 mono_thread_create (mono_get_root_domain (), async_invoke_thread, ares);
1026 append_job (&mono_delegate_section, &async_call_queue, ares);
1027 ReleaseSemaphore (job_added, 1, NULL);
1032 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1039 /* check if already finished */
1040 mono_monitor_enter ((MonoObject *) ares);
1042 if (ares->endinvoke_called) {
1043 *exc = (MonoObject *)mono_exception_from_name (mono_defaults.corlib, "System",
1044 "InvalidOperationException");
1045 mono_monitor_exit ((MonoObject *) ares);
1049 ares->endinvoke_called = 1;
1050 ac = (ASyncCall *)ares->data;
1052 g_assert (ac != NULL);
1054 /* wait until we are really finished */
1055 if (!ares->completed) {
1056 if (ares->handle == NULL) {
1057 ac->wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1058 MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), ac->wait_event));
1060 mono_monitor_exit ((MonoObject *) ares);
1061 WaitForSingleObjectEx (ac->wait_event, INFINITE, TRUE);
1063 mono_monitor_exit ((MonoObject *) ares);
1066 *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1067 *out_args = ac->out_args;
1073 mono_thread_pool_cleanup (void)
1077 EnterCriticalSection (&mono_delegate_section);
1078 g_list_free (async_call_queue);
1079 async_call_queue = NULL;
1080 release = (gint) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1081 LeaveCriticalSection (&mono_delegate_section);
1083 ReleaseSemaphore (job_added, release, NULL);
1085 socket_io_cleanup (&socket_io_data);
1089 append_job (CRITICAL_SECTION *cs, GList **plist, gpointer ar)
1093 EnterCriticalSection (cs);
1096 list = g_list_append (list, ar);
1098 for (tmp = list; tmp && tmp->data != NULL; tmp = tmp->next);
1100 list = g_list_append (list, ar);
1106 LeaveCriticalSection (cs);
1110 dequeue_job (CRITICAL_SECTION *cs, GList **plist)
1113 GList *tmp, *tmp2, *list;
1115 EnterCriticalSection (cs);
1122 for (tmp2 = tmp; tmp2->next != NULL; tmp2 = tmp2->next);
1131 LeaveCriticalSection (cs);
1137 async_invoke_thread (gpointer data)
1143 thread = mono_thread_current ();
1144 thread->threadpool_thread = TRUE;
1145 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
1148 MonoAsyncResult *ar;
1150 ar = (MonoAsyncResult *) data;
1152 /* worker threads invokes methods in different domains,
1153 * so we need to set the right domain here */
1154 domain = ((MonoObject *)ar)->vtable->domain;
1155 mono_thread_push_appdomain_ref (domain);
1156 if (mono_domain_set (domain, FALSE)) {
1159 mono_async_invoke (ar);
1160 ac = (ASyncCall *) ar->data;
1162 if (ac->msg->exc != NULL)
1163 mono_unhandled_exception (ac->msg->exc);
1165 mono_domain_set (mono_get_root_domain (), TRUE);
1167 mono_thread_pop_appdomain_ref ();
1168 InterlockedDecrement (&busy_worker_threads);
1171 data = dequeue_job (&mono_delegate_section, &async_call_queue);
1175 int timeout = 10000;
1176 guint32 start_time = GetTickCount ();
1179 wr = WaitForSingleObjectEx (job_added, (guint32)timeout, TRUE);
1180 if (THREAD_WANTS_A_BREAK (thread))
1181 mono_thread_interruption_checkpoint ();
1183 timeout -= GetTickCount () - start_time;
1185 if (wr != WAIT_TIMEOUT)
1186 data = dequeue_job (&mono_delegate_section, &async_call_queue);
1188 while (!data && timeout > 0);
1192 workers = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1193 min = (int) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
1195 while (!data && workers <= min) {
1196 WaitForSingleObjectEx (job_added, INFINITE, TRUE);
1197 if (THREAD_WANTS_A_BREAK (thread))
1198 mono_thread_interruption_checkpoint ();
1200 data = dequeue_job (&mono_delegate_section, &async_call_queue);
1201 workers = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1202 min = (int) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
1207 InterlockedDecrement (&mono_worker_threads);
1211 InterlockedIncrement (&busy_worker_threads);
1214 g_assert_not_reached ();
1218 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
1222 MONO_ARCH_SAVE_REGS;
1224 busy = (gint) InterlockedCompareExchange (&busy_worker_threads, 0, -1);
1225 *workerThreads = mono_max_worker_threads - busy;
1226 *completionPortThreads = 0;
1230 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
1232 MONO_ARCH_SAVE_REGS;
1234 *workerThreads = mono_max_worker_threads;
1235 *completionPortThreads = 0;
1239 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
1243 MONO_ARCH_SAVE_REGS;
1245 workers = (gint) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
1246 *workerThreads = workers;
1247 *completionPortThreads = 0;
1251 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
1253 MONO_ARCH_SAVE_REGS;
1255 if (workerThreads < 0 || workerThreads > mono_max_worker_threads)
1257 InterlockedExchange (&mono_min_worker_threads, workerThreads);
1258 /* FIXME: should actually start the idle threads if needed */