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 if (mono_domain_set (domain, FALSE)) {
246 mono_thread_push_appdomain_ref (domain);
247 mono_async_invoke (ar);
248 ac = (ASyncCall *) ar->data;
249 if (ac->msg->exc != NULL)
250 mono_unhandled_exception (ac->msg->exc);
251 mono_thread_pop_appdomain_ref ();
253 InterlockedDecrement (&busy_io_worker_threads);
256 data = dequeue_job (&io_queue_lock, &async_io_queue);
261 guint32 start_time = GetTickCount ();
264 wr = WaitForSingleObjectEx (io_job_added, (guint32)timeout, TRUE);
265 if (THREAD_WANTS_A_BREAK (thread))
266 mono_thread_interruption_checkpoint ();
268 timeout -= GetTickCount () - start_time;
270 if (wr != WAIT_TIMEOUT)
271 data = dequeue_job (&io_queue_lock, &async_io_queue);
273 while (!data && timeout > 0);
277 if (InterlockedDecrement (&io_worker_threads) < 2) {
278 /* If we have pending items, keep the thread alive */
279 if (InterlockedCompareExchange (&pending_io_items, 0, 0) != 0) {
280 InterlockedIncrement (&io_worker_threads);
287 InterlockedIncrement (&busy_io_worker_threads);
290 g_assert_not_reached ();
294 start_io_thread_or_queue (MonoSocketAsyncResult *ares)
299 busy = (int) InterlockedCompareExchange (&busy_io_worker_threads, 0, -1);
300 worker = (int) InterlockedCompareExchange (&io_worker_threads, 0, -1);
301 if (worker <= ++busy &&
302 worker < mono_io_max_worker_threads) {
303 InterlockedIncrement (&busy_io_worker_threads);
304 InterlockedIncrement (&io_worker_threads);
305 domain = ((ares) ? ((MonoObject *) ares)->vtable->domain : mono_domain_get ());
306 mono_thread_create (domain, async_invoke_io_thread, ares);
308 append_job (&io_queue_lock, &async_io_queue, ares);
309 ReleaseSemaphore (io_job_added, 1, NULL);
314 process_io_event (GSList *list, int event)
316 MonoSocketAsyncResult *state;
322 state = (MonoSocketAsyncResult *) list->data;
323 if (get_event_from_state (state) == event)
330 oldlist = g_slist_remove_link (oldlist, list);
331 g_slist_free_1 (list);
333 g_print ("Dispatching event %d on socket %d\n", event, state->handle);
335 InterlockedIncrement (&pending_io_items);
336 start_io_thread_or_queue (state);
343 mark_bad_fds (mono_pollfd *pfds, int nfds)
349 for (i = 0; i < nfds; i++) {
354 ret = mono_poll (pfds, 1, 0);
355 if (ret == -1 && errno == EBADF) {
356 pfd->revents |= MONO_POLLNVAL;
358 } else if (ret == 1) {
367 socket_io_poll_main (gpointer p)
369 #define INITIAL_POLLFD_SIZE 1024
370 #define POLL_ERRORS (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL)
371 SocketIOData *data = p;
378 thread = mono_thread_current ();
379 thread->threadpool_thread = TRUE;
380 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
382 allocated = INITIAL_POLLFD_SIZE;
383 pfds = g_new0 (mono_pollfd, allocated);
384 INIT_POLLFD (pfds, data->pipe [0], MONO_POLLIN);
385 for (i = 1; i < allocated; i++)
386 INIT_POLLFD (&pfds [i], -1, 0);
396 if (THREAD_WANTS_A_BREAK (thread))
397 mono_thread_interruption_checkpoint ();
400 nsock = mono_poll (pfds, maxfd, -1);
401 } while (nsock == -1 && errno == EINTR);
404 * Apart from EINTR, we only check EBADF, for the rest:
405 * EINVAL: mono_poll() 'protects' us from descriptor
406 * numbers above the limit if using select() by marking
407 * then as MONO_POLLERR. If a system poll() is being
408 * used, the number of descriptor we're passing will not
409 * be over sysconf(_SC_OPEN_MAX), as the error would have
410 * happened when opening.
412 * EFAULT: we own the memory pointed by pfds.
413 * ENOMEM: we're doomed anyway
417 if (nsock == -1 && errno == EBADF) {
418 pfds->revents = 0; /* Just in case... */
419 nsock = mark_bad_fds (pfds, maxfd);
422 if ((pfds->revents & POLL_ERRORS) != 0) {
423 /* We're supposed to die now, as the pipe has been closed */
425 socket_io_cleanup (data);
429 /* Got a new socket */
430 if ((pfds->revents & MONO_POLLIN) != 0) {
433 for (i = 1; i < allocated; i++) {
435 if (pfd->fd == -1 || pfd->fd == data->newpfd->fd)
439 if (i == allocated) {
444 allocated = allocated * 2;
445 pfds = g_renew (mono_pollfd, oldfd, allocated);
447 for (; i < allocated; i++)
448 INIT_POLLFD (&pfds [i], -1, 0);
450 #ifndef PLATFORM_WIN32
451 nread = read (data->pipe [0], one, 1);
453 nread = recv ((SOCKET) data->pipe [0], one, 1, 0);
457 return; /* we're closed */
460 INIT_POLLFD (&pfds [i], data->newpfd->fd, data->newpfd->events);
461 ReleaseSemaphore (data->new_sem, 1, NULL);
470 EnterCriticalSection (&data->io_lock);
471 if (data->inited == 0) {
473 return; /* cleanup called */
476 for (i = 1; i < maxfd && nsock > 0; i++) {
478 if (pfd->fd == -1 || pfd->revents == 0)
482 list = g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
483 if (list != NULL && (pfd->revents & (MONO_POLLIN | POLL_ERRORS)) != 0) {
484 list = process_io_event (list, MONO_POLLIN);
487 if (list != NULL && (pfd->revents & (MONO_POLLOUT | POLL_ERRORS)) != 0) {
488 list = process_io_event (list, MONO_POLLOUT);
492 g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (pfd->fd), list);
493 pfd->events = get_events_from_list (list);
495 g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
501 LeaveCriticalSection (&data->io_lock);
506 #define EPOLL_ERRORS (EPOLLERR | EPOLLHUP)
508 socket_io_epoll_main (gpointer p)
513 struct epoll_event *events, *evt;
514 const int nevents = 512;
518 epollfd = data->epollfd;
519 thread = mono_thread_current ();
520 thread->threadpool_thread = TRUE;
521 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
522 events = g_new0 (struct epoll_event, nevents);
527 if (THREAD_WANTS_A_BREAK (thread))
528 mono_thread_interruption_checkpoint ();
531 g_print ("epoll_wait init\n");
533 ready = epoll_wait (epollfd, events, nevents, -1);
537 g_print ("epoll_wait end with %d ready sockets (%d %s).\n", ready, err, (err) ? g_strerror (err) : "");
541 } while (ready == -1 && errno == EINTR);
547 g_warning ("epoll_wait: %d %s\n", err, g_strerror (err));
553 EnterCriticalSection (&data->io_lock);
554 if (data->inited == 0) {
556 g_print ("data->inited == 0\n");
560 return; /* cleanup called */
563 for (i = 0; i < ready; i++) {
569 list = g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
571 g_print ("Event %d on %d list length: %d\n", evt->events, fd, g_slist_length (list));
573 if (list != NULL && (evt->events & (EPOLLIN | EPOLL_ERRORS)) != 0) {
574 list = process_io_event (list, MONO_POLLIN);
577 if (list != NULL && (evt->events & (EPOLLOUT | EPOLL_ERRORS)) != 0) {
578 list = process_io_event (list, MONO_POLLOUT);
582 g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (fd), list);
583 evt->events = get_events_from_list (list);
585 g_print ("MOD %d to %d\n", fd, evt->events);
587 if (epoll_ctl (epollfd, EPOLL_CTL_MOD, fd, evt)) {
588 if (epoll_ctl (epollfd, EPOLL_CTL_ADD, fd, evt) == -1) {
591 g_message ("epoll_ctl(MOD): %d %s fd: %d events: %d", err, g_strerror (err), fd, evt->events);
597 g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (fd));
599 g_print ("DEL %d\n", fd);
601 epoll_ctl (epollfd, EPOLL_CTL_DEL, fd, evt);
604 LeaveCriticalSection (&data->io_lock);
610 * select/poll wake up when a socket is closed, but epoll just removes
611 * the socket from its internal list without notification.
614 mono_thread_pool_remove_socket (int sock)
618 MonoSocketAsyncResult *state;
620 if (socket_io_data.epoll_disabled == TRUE || socket_io_data.inited == FALSE)
623 EnterCriticalSection (&socket_io_data.io_lock);
624 list = g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
626 g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
628 LeaveCriticalSection (&socket_io_data.io_lock);
631 state = (MonoSocketAsyncResult *) list->data;
632 if (state->operation == AIO_OP_RECEIVE)
633 state->operation = AIO_OP_RECV_JUST_CALLBACK;
634 else if (state->operation == AIO_OP_SEND)
635 state->operation = AIO_OP_SEND_JUST_CALLBACK;
637 next = g_slist_remove_link (list, list);
638 list = process_io_event (list, MONO_POLLIN);
640 process_io_event (list, MONO_POLLOUT);
647 #ifdef PLATFORM_WIN32
649 connect_hack (gpointer x)
651 struct sockaddr_in *addr = (struct sockaddr_in *) x;
654 while (connect ((SOCKET) socket_io_data.pipe [1], (SOCKADDR *) addr, sizeof (struct sockaddr_in))) {
657 g_warning ("Error initializing async. sockets %d.\n", WSAGetLastError ());
658 g_assert (WSAGetLastError ());
665 socket_io_init (SocketIOData *data)
667 #ifdef PLATFORM_WIN32
668 struct sockaddr_in server;
669 struct sockaddr_in client;
675 inited = InterlockedCompareExchange (&data->inited, -1, -1);
679 EnterCriticalSection (&data->io_lock);
680 inited = InterlockedCompareExchange (&data->inited, -1, -1);
682 LeaveCriticalSection (&data->io_lock);
687 data->epoll_disabled = (g_getenv ("MONO_DISABLE_AIO") != NULL);
688 if (FALSE == data->epoll_disabled) {
689 data->epollfd = epoll_create (256);
690 data->epoll_disabled = (data->epollfd == -1);
691 if (data->epoll_disabled && g_getenv ("MONO_DEBUG"))
692 g_message ("epoll_create() failed. Using plain poll().");
697 data->epoll_disabled = TRUE;
700 #ifndef PLATFORM_WIN32
701 if (data->epoll_disabled) {
702 if (pipe (data->pipe) != 0) {
712 srv = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
713 g_assert (srv != INVALID_SOCKET);
714 data->pipe [1] = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
715 g_assert (data->pipe [1] != INVALID_SOCKET);
717 server.sin_family = AF_INET;
718 server.sin_addr.s_addr = inet_addr ("127.0.0.1");
720 if (bind (srv, (SOCKADDR *) &server, sizeof (server))) {
721 g_print ("%d\n", WSAGetLastError ());
725 len = sizeof (server);
726 getsockname (srv, (SOCKADDR *) &server, &len);
728 mono_thread_create (mono_get_root_domain (), connect_hack, &server);
729 len = sizeof (server);
730 data->pipe [0] = accept (srv, (SOCKADDR *) &client, &len);
731 g_assert (data->pipe [0] != INVALID_SOCKET);
734 mono_io_max_worker_threads = mono_max_worker_threads / 2;
735 if (mono_io_max_worker_threads < 10)
736 mono_io_max_worker_threads = 10;
738 data->sock_to_state = g_hash_table_new (g_direct_hash, g_direct_equal);
740 if (data->epoll_disabled)
741 data->new_sem = CreateSemaphore (NULL, 1, 1, NULL);
742 io_job_added = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
743 InitializeCriticalSection (&io_queue_lock);
744 if (data->epoll_disabled) {
745 mono_thread_create (mono_get_root_domain (), socket_io_poll_main, data);
749 mono_thread_create (mono_get_root_domain (), socket_io_epoll_main, data);
752 InterlockedCompareExchange (&data->inited, 1, 0);
753 LeaveCriticalSection (&data->io_lock);
757 socket_io_add_poll (MonoSocketAsyncResult *state)
762 SocketIOData *data = &socket_io_data;
764 WaitForSingleObject (data->new_sem, INFINITE);
765 if (data->newpfd == NULL)
766 data->newpfd = g_new0 (mono_pollfd, 1);
768 EnterCriticalSection (&data->io_lock);
769 list = g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (state->handle));
771 list = g_slist_alloc ();
774 list = g_slist_append (list, state);
777 events = get_events_from_list (list);
778 INIT_POLLFD (data->newpfd, GPOINTER_TO_INT (state->handle), events);
779 g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (state->handle), list);
780 LeaveCriticalSection (&data->io_lock);
781 *msg = (char) state->operation;
782 #ifndef PLATFORM_WIN32
783 write (data->pipe [1], msg, 1);
785 send ((SOCKET) data->pipe [1], msg, 1, 0);
791 socket_io_add_epoll (MonoSocketAsyncResult *state)
794 SocketIOData *data = &socket_io_data;
795 struct epoll_event event;
799 memset (&event, 0, sizeof (struct epoll_event));
800 fd = GPOINTER_TO_INT (state->handle);
801 EnterCriticalSection (&data->io_lock);
802 list = g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
804 list = g_slist_alloc ();
806 epoll_op = EPOLL_CTL_ADD;
808 list = g_slist_append (list, state);
809 epoll_op = EPOLL_CTL_MOD;
812 ievt = get_events_from_list (list);
813 if ((ievt & MONO_POLLIN) != 0)
814 event.events |= EPOLLIN;
815 if ((ievt & MONO_POLLOUT) != 0)
816 event.events |= EPOLLOUT;
818 g_hash_table_replace (data->sock_to_state, state->handle, list);
821 g_print ("%s %d with %d\n", epoll_op == EPOLL_CTL_ADD ? "ADD" : "MOD", fd, event.events);
823 if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
825 if (epoll_op == EPOLL_CTL_ADD && err == EEXIST) {
826 epoll_op = EPOLL_CTL_MOD;
827 if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
828 g_message ("epoll_ctl(MOD): %d %s\n", err, g_strerror (err));
833 LeaveCriticalSection (&data->io_lock);
839 socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
841 socket_io_init (&socket_io_data);
844 if (socket_io_data.epoll_disabled == FALSE) {
845 if (socket_io_add_epoll (state))
849 socket_io_add_poll (state);
853 socket_io_filter (MonoObject *target, MonoObject *state)
856 MonoSocketAsyncResult *sock_res = (MonoSocketAsyncResult *) state;
859 if (target == NULL || state == NULL)
862 if (socket_async_call_klass == NULL) {
863 klass = target->vtable->klass;
864 /* Check if it's SocketAsyncCall in System
865 * FIXME: check the assembly is signed correctly for extra care
867 if (klass->name [0] == 'S' && strcmp (klass->name, "SocketAsyncCall") == 0
868 && strcmp (mono_image_get_name (klass->image), "System") == 0
869 && klass->nested_in && strcmp (klass->nested_in->name, "Socket") == 0)
870 socket_async_call_klass = klass;
873 /* return both when socket_async_call_klass has not been seen yet and when
874 * the object is not an instance of the class.
876 if (target->vtable->klass != socket_async_call_klass)
879 op = sock_res->operation;
880 if (op < AIO_OP_FIRST || op >= AIO_OP_LAST)
887 mono_async_invoke (MonoAsyncResult *ares)
889 ASyncCall *ac = (ASyncCall *)ares->data;
892 ac->res = mono_message_invoke (ares->async_delegate, ac->msg,
893 &ac->msg->exc, &ac->out_args);
897 /* call async callback if cb_method != null*/
899 MonoObject *exc = NULL;
901 mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &exc);
906 /* notify listeners */
907 mono_monitor_enter ((MonoObject *) ares);
908 if (ares->handle != NULL) {
909 ac->wait_event = ((MonoWaitHandle *) ares->handle)->handle;
910 SetEvent (ac->wait_event);
912 mono_monitor_exit ((MonoObject *) ares);
914 EnterCriticalSection (&ares_lock);
915 mono_g_hash_table_remove (ares_htable, ares);
916 LeaveCriticalSection (&ares_lock);
920 mono_thread_pool_init ()
923 int threads_per_cpu = THREADS_PER_CPU;
925 if ((int) InterlockedCompareExchange (&tp_inited, 1, 0) == 1)
928 MONO_GC_REGISTER_ROOT (ares_htable);
929 InitializeCriticalSection (&socket_io_data.io_lock);
930 InitializeCriticalSection (&ares_lock);
931 ares_htable = mono_g_hash_table_new (NULL, NULL);
932 job_added = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
933 GetSystemInfo (&info);
934 if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
935 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
936 if (threads_per_cpu <= 0)
937 threads_per_cpu = THREADS_PER_CPU;
940 mono_max_worker_threads = 20 + threads_per_cpu * info.dwNumberOfProcessors;
944 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
947 MonoDomain *domain = mono_domain_get ();
948 MonoAsyncResult *ares;
952 ac = GC_MALLOC (sizeof (ASyncCall));
954 /* We'll leak the event if creaated... */
955 ac = g_new0 (ASyncCall, 1);
957 ac->wait_event = NULL;
961 if (async_callback) {
962 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
963 ac->cb_target = async_callback;
966 ares = mono_async_result_new (domain, NULL, ac->state, ac);
967 ares->async_delegate = target;
969 EnterCriticalSection (&ares_lock);
970 mono_g_hash_table_insert (ares_htable, ares, ares);
971 LeaveCriticalSection (&ares_lock);
973 if (socket_io_filter (target, state)) {
974 socket_io_add (ares, (MonoSocketAsyncResult *) state);
978 start_thread_or_queue (ares);
983 start_thread_or_queue (MonoAsyncResult *ares)
988 busy = (int) InterlockedCompareExchange (&busy_worker_threads, 0, -1);
989 worker = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
990 if (worker <= ++busy &&
991 worker < mono_max_worker_threads) {
992 InterlockedIncrement (&mono_worker_threads);
993 InterlockedIncrement (&busy_worker_threads);
994 domain = ((MonoObject *) ares)->vtable->domain;
995 mono_thread_create (domain, async_invoke_thread, ares);
997 append_job (&mono_delegate_section, &async_call_queue, ares);
998 ReleaseSemaphore (job_added, 1, NULL);
1003 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1010 /* check if already finished */
1011 mono_monitor_enter ((MonoObject *) ares);
1013 if (ares->endinvoke_called) {
1014 *exc = (MonoObject *)mono_exception_from_name (mono_defaults.corlib, "System",
1015 "InvalidOperationException");
1016 mono_monitor_exit ((MonoObject *) ares);
1020 ares->endinvoke_called = 1;
1021 ac = (ASyncCall *)ares->data;
1023 g_assert (ac != NULL);
1025 /* wait until we are really finished */
1026 if (!ares->completed) {
1027 if (ares->handle == NULL) {
1028 ac->wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1029 ares->handle = (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), ac->wait_event);
1031 mono_monitor_exit ((MonoObject *) ares);
1032 WaitForSingleObjectEx (ac->wait_event, INFINITE, TRUE);
1034 mono_monitor_exit ((MonoObject *) ares);
1037 *exc = ac->msg->exc;
1038 *out_args = ac->out_args;
1044 mono_thread_pool_cleanup (void)
1048 EnterCriticalSection (&mono_delegate_section);
1049 g_list_free (async_call_queue);
1050 async_call_queue = NULL;
1051 release = (gint) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1052 LeaveCriticalSection (&mono_delegate_section);
1054 ReleaseSemaphore (job_added, release, NULL);
1056 socket_io_cleanup (&socket_io_data);
1060 append_job (CRITICAL_SECTION *cs, GList **plist, gpointer ar)
1064 EnterCriticalSection (cs);
1067 list = g_list_append (list, ar);
1069 for (tmp = list; tmp && tmp->data != NULL; tmp = tmp->next);
1071 list = g_list_append (list, ar);
1077 LeaveCriticalSection (cs);
1081 dequeue_job (CRITICAL_SECTION *cs, GList **plist)
1084 GList *tmp, *tmp2, *list;
1086 EnterCriticalSection (cs);
1093 for (tmp2 = tmp; tmp2->next != NULL; tmp2 = tmp2->next);
1102 LeaveCriticalSection (cs);
1108 async_invoke_thread (gpointer data)
1114 thread = mono_thread_current ();
1115 thread->threadpool_thread = TRUE;
1116 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
1119 MonoAsyncResult *ar;
1121 ar = (MonoAsyncResult *) data;
1123 /* worker threads invokes methods in different domains,
1124 * so we need to set the right domain here */
1125 domain = ((MonoObject *)ar)->vtable->domain;
1126 if (mono_domain_set (domain, FALSE)) {
1129 mono_thread_push_appdomain_ref (domain);
1130 mono_async_invoke (ar);
1131 ac = (ASyncCall *) ar->data;
1132 if (ac->msg->exc != NULL)
1133 mono_unhandled_exception (ac->msg->exc);
1134 mono_thread_pop_appdomain_ref ();
1136 InterlockedDecrement (&busy_worker_threads);
1139 data = dequeue_job (&mono_delegate_section, &async_call_queue);
1143 int timeout = 10000;
1144 guint32 start_time = GetTickCount ();
1147 wr = WaitForSingleObjectEx (job_added, (guint32)timeout, TRUE);
1148 if (THREAD_WANTS_A_BREAK (thread))
1149 mono_thread_interruption_checkpoint ();
1151 timeout -= GetTickCount () - start_time;
1153 if (wr != WAIT_TIMEOUT)
1154 data = dequeue_job (&mono_delegate_section, &async_call_queue);
1156 while (!data && timeout > 0);
1160 workers = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1161 min = (int) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
1163 while (!data && workers <= min) {
1164 WaitForSingleObjectEx (job_added, INFINITE, TRUE);
1165 if (THREAD_WANTS_A_BREAK (thread))
1166 mono_thread_interruption_checkpoint ();
1168 data = dequeue_job (&mono_delegate_section, &async_call_queue);
1169 workers = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1170 min = (int) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
1175 InterlockedDecrement (&mono_worker_threads);
1179 InterlockedIncrement (&busy_worker_threads);
1182 g_assert_not_reached ();
1186 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
1190 MONO_ARCH_SAVE_REGS;
1192 busy = (gint) InterlockedCompareExchange (&busy_worker_threads, 0, -1);
1193 *workerThreads = mono_max_worker_threads - busy;
1194 *completionPortThreads = 0;
1198 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
1200 MONO_ARCH_SAVE_REGS;
1202 *workerThreads = mono_max_worker_threads;
1203 *completionPortThreads = 0;
1207 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
1211 MONO_ARCH_SAVE_REGS;
1213 workers = (gint) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
1214 *workerThreads = workers;
1215 *completionPortThreads = 0;
1219 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
1221 MONO_ARCH_SAVE_REGS;
1223 if (workerThreads < 0 || workerThreads > mono_max_worker_threads)
1225 InterlockedExchange (&mono_min_worker_threads, workerThreads);
1226 /* FIXME: should actually start the idle threads if needed */