2 * threadpool.c: global thread pool
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Gonzalo Paniagua Javier (gonzalo@ximian.com)
8 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
9 * Copyright 2004-2010 Novell, Inc (http://www.novell.com)
15 #ifdef MONO_SMALL_CONFIG
16 #define QUEUE_LENGTH 16 /* Must be 2^N */
18 #define QUEUE_LENGTH 64 /* Must be 2^N */
21 #include <mono/metadata/domain-internals.h>
22 #include <mono/metadata/tabledefs.h>
23 #include <mono/metadata/threads.h>
24 #include <mono/metadata/threads-types.h>
25 #include <mono/metadata/threadpool-internals.h>
26 #include <mono/metadata/exception.h>
27 #include <mono/metadata/file-io.h>
28 #include <mono/metadata/monitor.h>
29 #include <mono/metadata/mono-mlist.h>
30 #include <mono/metadata/marshal.h>
31 #include <mono/metadata/mono-perfcounters.h>
32 #include <mono/metadata/socket-io.h>
33 #include <mono/metadata/mono-wsq.h>
34 #include <mono/io-layer/io-layer.h>
35 #include <mono/metadata/gc-internal.h>
36 #include <mono/utils/mono-time.h>
37 #include <mono/utils/mono-proclib.h>
38 #include <mono/utils/mono-semaphore.h>
40 #ifdef HAVE_SYS_TIME_H
43 #include <sys/types.h>
49 #ifdef HAVE_SYS_SOCKET_H
50 #include <sys/socket.h>
52 #include <mono/utils/mono-poll.h>
54 #include <sys/epoll.h>
57 #ifndef DISABLE_SOCKETS
58 #include "mono/io-layer/socket-wrappers.h"
61 #include "threadpool.h"
63 #define THREAD_WANTS_A_BREAK(t) ((t->state & (ThreadState_StopRequested | \
64 ThreadState_SuspendRequested)) != 0)
66 #define SPIN_TRYLOCK(i) (InterlockedCompareExchange (&(i), 1, 0) == 0)
67 #define SPIN_LOCK(i) do { \
68 if (SPIN_TRYLOCK (i)) \
72 #define SPIN_UNLOCK(i) i = 0
74 #define EPOLL_DEBUG(...)
75 #define EPOLL_DEBUG_STMT(...)
77 #define TP_DEBUG_STMT(...)
79 /* DEBUG: prints tp data every 2s */
83 #define EPOLL_DEBUG(...) g_message(__VA_ARGS__)
84 #define EPOLL_DEBUG_STMT(...) do { __VA_ARGS__ } while (0)
85 #define TP_DEBUG(...) g_message(__VA_ARGS__)
86 #define TP_DEBUG_STMT(...) do { __VA_ARGS__ } while (0)
89 /* map of CounterSample.cs */
90 struct _MonoCounterSample {
93 gint64 counterFrequency;
94 gint64 systemFrequency;
96 gint64 timeStamp100nSec;
97 gint64 counterTimeStamp;
101 /* mono_thread_pool_init called */
102 static volatile int tp_inited;
105 CRITICAL_SECTION io_lock; /* access to sock_to_state */
106 int inited; // 0 -> not initialized , 1->initializing, 2->initialized, 3->cleaned up
108 MonoGHashTable *sock_to_state;
110 HANDLE new_sem; /* access to newpfd and write side of the pipe */
112 gboolean epoll_disabled;
118 static SocketIOData socket_io_data;
120 /* Keep in sync with the System.MonoAsyncCall class which provides GC tracking */
123 MonoMethodMessage *msg;
124 MonoMethod *cb_method;
125 MonoDelegate *cb_target;
133 MonoMList *first; /* GC root */
135 MonoMList *unused; /* Up to 20 chunks. GC root */
139 volatile gint waiting; /* threads waiting for a work item */
142 volatile gint pool_status; /* 0 -> not initialized, 1 -> initialized, 2 -> cleaning up */
143 /* min, max, n and busy -> Interlocked */
144 volatile gint min_threads;
145 volatile gint max_threads;
146 volatile gint nthreads;
147 volatile gint busy_threads;
149 void (*async_invoke) (gpointer data);
150 void *pc_nitems; /* Performance counter for total number of items in added */
151 void *pc_nthreads; /* Performance counter for total number of active threads */
153 volatile gint destroy_thread;
154 volatile gint ignore_times; /* Used when there's a thread being created or destroyed */
155 volatile gint sp_lock; /* spin lock used to protect ignore_times */
156 volatile gint64 last_check;
157 volatile gint64 time_sum;
161 //TP_DEBUG_ONLY (gint nodes_created);
162 //TP_DEBUG_ONLY (gint nodes_reused);
166 static ThreadPool async_tp;
167 static ThreadPool async_io_tp;
169 static void async_invoke_thread (gpointer data);
170 static MonoObject *mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares);
171 static void threadpool_free_queue (ThreadPool *tp);
172 static void threadpool_append_job (ThreadPool *tp, MonoObject *ar);
173 static void threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs);
174 static void threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer));
175 static void threadpool_start_idle_threads (ThreadPool *tp);
176 static void threadpool_kill_idle_threads (ThreadPool *tp);
178 static MonoClass *async_call_klass;
179 static MonoClass *socket_async_call_klass;
180 static MonoClass *process_async_call_klass;
182 static GPtrArray *wsqs;
183 CRITICAL_SECTION wsqs_lock;
186 static MonoThreadPoolFunc tp_start_func;
187 static MonoThreadPoolFunc tp_finish_func;
188 static gpointer tp_hooks_user_data;
189 static MonoThreadPoolItemFunc tp_item_begin_func;
190 static MonoThreadPoolItemFunc tp_item_end_func;
191 static gpointer tp_item_user_data;
193 #define INIT_POLLFD(a, b, c) {(a)->fd = b; (a)->events = c; (a)->revents = 0;}
202 AIO_OP_RECV_JUST_CALLBACK,
203 AIO_OP_SEND_JUST_CALLBACK,
208 #ifdef DISABLE_SOCKETS
209 #define socket_io_cleanup(x)
212 socket_io_cleanup (SocketIOData *data)
214 EnterCriticalSection (&data->io_lock);
215 if (data->inited != 2) {
216 LeaveCriticalSection (&data->io_lock);
222 closesocket (data->pipe [0]);
223 closesocket (data->pipe [1]);
225 if (data->pipe [0] > -1)
226 close (data->pipe [0]);
227 if (data->pipe [1] > -1)
228 close (data->pipe [1]);
233 CloseHandle (data->new_sem);
234 data->new_sem = NULL;
235 mono_g_hash_table_destroy (data->sock_to_state);
236 data->sock_to_state = NULL;
237 g_free (data->newpfd);
240 if (FALSE == data->epoll_disabled)
241 close (data->epollfd);
243 LeaveCriticalSection (&data->io_lock);
247 get_event_from_state (MonoSocketAsyncResult *state)
249 switch (state->operation) {
252 case AIO_OP_RECV_JUST_CALLBACK:
253 case AIO_OP_RECEIVEFROM:
254 case AIO_OP_READPIPE:
257 case AIO_OP_SEND_JUST_CALLBACK:
261 default: /* Should never happen */
262 g_message ("get_event_from_state: unknown value in switch!!!");
268 get_events_from_list (MonoMList *list)
270 MonoSocketAsyncResult *state;
273 while (list && (state = (MonoSocketAsyncResult *)mono_mlist_get_data (list))) {
274 events |= get_event_from_state (state);
275 list = mono_mlist_next (list);
281 #define ICALL_RECV(x) ves_icall_System_Net_Sockets_Socket_Receive_internal (\
282 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
283 x->socket_flags, &x->error);
285 #define ICALL_SEND(x) ves_icall_System_Net_Sockets_Socket_Send_internal (\
286 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
287 x->socket_flags, &x->error);
289 #endif /* !DISABLE_SOCKETS */
292 threadpool_jobs_inc (MonoObject *obj)
295 InterlockedIncrement (&obj->vtable->domain->threadpool_jobs);
299 threadpool_jobs_dec (MonoObject *obj)
301 MonoDomain *domain = obj->vtable->domain;
302 int remaining_jobs = InterlockedDecrement (&domain->threadpool_jobs);
303 if (remaining_jobs == 0 && domain->cleanup_semaphore) {
304 ReleaseSemaphore (domain->cleanup_semaphore, 1, NULL);
312 get_io_event (MonoMList **list, gint event)
322 state = mono_mlist_get_data (current);
323 if (get_event_from_state ((MonoSocketAsyncResult *) state) == event)
328 current = mono_mlist_next (current);
333 mono_mlist_set_next (prev, mono_mlist_next (current));
335 *list = mono_mlist_next (*list);
344 process_io_event (MonoMList *list, int event)
346 MonoSocketAsyncResult *state;
352 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
353 if (get_event_from_state (state) == event)
356 list = mono_mlist_next (list);
360 oldlist = mono_mlist_remove_item (oldlist, list);
361 EPOLL_DEBUG ("Dispatching event %d on socket %p", event, state->handle);
362 threadpool_append_job (&async_io_tp, (MonoObject *) state);
369 mark_bad_fds (mono_pollfd *pfds, int nfds)
375 for (i = 0; i < nfds; i++) {
380 ret = mono_poll (pfd, 1, 0);
381 if (ret == -1 && errno == EBADF) {
382 pfd->revents |= MONO_POLLNVAL;
384 } else if (ret == 1) {
393 socket_io_poll_main (gpointer p)
395 #if MONO_SMALL_CONFIG
396 #define INITIAL_POLLFD_SIZE 128
398 #define INITIAL_POLLFD_SIZE 1024
400 #define POLL_ERRORS (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL)
401 SocketIOData *data = p;
406 MonoInternalThread *thread;
408 thread = mono_thread_internal_current ();
410 allocated = INITIAL_POLLFD_SIZE;
411 pfds = g_new0 (mono_pollfd, allocated);
412 INIT_POLLFD (pfds, data->pipe [0], MONO_POLLIN);
413 for (i = 1; i < allocated; i++)
414 INIT_POLLFD (&pfds [i], -1, 0);
424 if (THREAD_WANTS_A_BREAK (thread))
425 mono_thread_interruption_checkpoint ();
428 nsock = mono_poll (pfds, maxfd, -1);
429 } while (nsock == -1 && errno == EINTR);
432 * Apart from EINTR, we only check EBADF, for the rest:
433 * EINVAL: mono_poll() 'protects' us from descriptor
434 * numbers above the limit if using select() by marking
435 * then as MONO_POLLERR. If a system poll() is being
436 * used, the number of descriptor we're passing will not
437 * be over sysconf(_SC_OPEN_MAX), as the error would have
438 * happened when opening.
440 * EFAULT: we own the memory pointed by pfds.
441 * ENOMEM: we're doomed anyway
445 if (nsock == -1 && errno == EBADF) {
446 pfds->revents = 0; /* Just in case... */
447 nsock = mark_bad_fds (pfds, maxfd);
450 if ((pfds->revents & POLL_ERRORS) != 0) {
451 /* We're supposed to die now, as the pipe has been closed */
453 socket_io_cleanup (data);
457 /* Got a new socket */
458 if ((pfds->revents & MONO_POLLIN) != 0) {
461 for (i = 1; i < allocated; i++) {
463 if (pfd->fd == -1 || data->newpfd == NULL ||
464 pfd->fd == data->newpfd->fd)
468 if (i == allocated) {
473 allocated = allocated * 2;
474 pfds = g_renew (mono_pollfd, oldfd, allocated);
476 for (; i < allocated; i++)
477 INIT_POLLFD (&pfds [i], -1, 0);
480 nread = read (data->pipe [0], one, 1);
482 nread = recv ((SOCKET) data->pipe [0], one, 1, 0);
486 return; /* we're closed */
489 INIT_POLLFD (&pfds [i], data->newpfd->fd, data->newpfd->events);
490 ReleaseSemaphore (data->new_sem, 1, NULL);
499 EnterCriticalSection (&data->io_lock);
500 if (data->inited == 3) {
502 LeaveCriticalSection (&data->io_lock);
503 return; /* cleanup called */
506 for (i = 1; i < maxfd && nsock > 0; i++) {
508 if (pfd->fd == -1 || pfd->revents == 0)
512 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
513 if (list != NULL && (pfd->revents & (MONO_POLLIN | POLL_ERRORS)) != 0) {
514 list = process_io_event (list, MONO_POLLIN);
517 if (list != NULL && (pfd->revents & (MONO_POLLOUT | POLL_ERRORS)) != 0) {
518 list = process_io_event (list, MONO_POLLOUT);
522 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (pfd->fd), list);
523 pfd->events = get_events_from_list (list);
525 mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
531 LeaveCriticalSection (&data->io_lock);
536 #define EPOLL_ERRORS (EPOLLERR | EPOLLHUP)
537 #define EPOLL_NEVENTS 128
539 socket_io_epoll_main (gpointer p)
543 MonoInternalThread *thread;
544 struct epoll_event *events, *evt;
546 gpointer async_results [EPOLL_NEVENTS * 2]; // * 2 because each loop can add up to 2 results here
550 epollfd = data->epollfd;
551 thread = mono_thread_internal_current ();
552 events = g_new0 (struct epoll_event, EPOLL_NEVENTS);
557 if (THREAD_WANTS_A_BREAK (thread))
558 mono_thread_interruption_checkpoint ();
560 EPOLL_DEBUG ("epoll_wait init");
561 ready = epoll_wait (epollfd, events, EPOLL_NEVENTS, -1);
564 EPOLL_DEBUG ("epoll_wait end with %d ready sockets (%d %s).", ready, err, (ready == -1) ? g_strerror (err) : "");
567 } while (ready == -1 && errno == EINTR);
573 g_warning ("epoll_wait: %d %s", err, g_strerror (err));
579 EnterCriticalSection (&data->io_lock);
580 if (data->inited == 3) {
583 LeaveCriticalSection (&data->io_lock);
584 return; /* cleanup called */
588 for (i = 0; i < ready; i++) {
595 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
596 EPOLL_DEBUG ("Event %d on %d list length: %d", evt->events, fd, mono_mlist_length (list));
597 if (list != NULL && (evt->events & (EPOLLIN | EPOLL_ERRORS)) != 0) {
598 ares = get_io_event (&list, MONO_POLLIN);
600 async_results [nresults++] = ares;
603 if (list != NULL && (evt->events & (EPOLLOUT | EPOLL_ERRORS)) != 0) {
604 ares = get_io_event (&list, MONO_POLLOUT);
606 async_results [nresults++] = ares;
610 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (fd), list);
611 evt->events = get_events_from_list (list);
612 EPOLL_DEBUG ("MOD %d to %d", fd, evt->events);
613 if (epoll_ctl (epollfd, EPOLL_CTL_MOD, fd, evt)) {
614 if (epoll_ctl (epollfd, EPOLL_CTL_ADD, fd, evt) == -1) {
617 EPOLL_DEBUG ("epoll_ctl(MOD): %d %s fd: %d events: %d", err, g_strerror (err), fd, evt->events);
623 mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (fd));
624 EPOLL_DEBUG ("DEL %d", fd);
625 epoll_ctl (epollfd, EPOLL_CTL_DEL, fd, evt);
628 LeaveCriticalSection (&data->io_lock);
629 threadpool_append_jobs (&async_io_tp, (MonoObject **) async_results, nresults);
630 memset (async_results, 0, sizeof (gpointer) * nresults);
637 * select/poll wake up when a socket is closed, but epoll just removes
638 * the socket from its internal list without notification.
641 mono_thread_pool_remove_socket (int sock)
643 MonoMList *list, *next;
644 MonoSocketAsyncResult *state;
646 if (socket_io_data.inited == 0)
649 EnterCriticalSection (&socket_io_data.io_lock);
650 if (socket_io_data.sock_to_state == NULL) {
651 LeaveCriticalSection (&socket_io_data.io_lock);
654 list = mono_g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
656 mono_g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
657 LeaveCriticalSection (&socket_io_data.io_lock);
660 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
661 if (state->operation == AIO_OP_RECEIVE)
662 state->operation = AIO_OP_RECV_JUST_CALLBACK;
663 else if (state->operation == AIO_OP_SEND)
664 state->operation = AIO_OP_SEND_JUST_CALLBACK;
666 next = mono_mlist_remove_item (list, list);
667 list = process_io_event (list, MONO_POLLIN);
669 process_io_event (list, MONO_POLLOUT);
677 connect_hack (gpointer x)
679 struct sockaddr_in *addr = (struct sockaddr_in *) x;
682 while (connect ((SOCKET) socket_io_data.pipe [1], (SOCKADDR *) addr, sizeof (struct sockaddr_in))) {
685 g_warning ("Error initializing async. sockets %d.", WSAGetLastError ());
686 g_assert (WSAGetLastError ());
693 socket_io_init (SocketIOData *data)
696 struct sockaddr_in server;
697 struct sockaddr_in client;
704 if (data->inited >= 2) // 2 -> initialized, 3-> cleaned up
707 inited = InterlockedCompareExchange (&data->inited, 1, 0);
710 if (data->inited >= 2)
716 EnterCriticalSection (&data->io_lock);
719 data->epoll_disabled = (g_getenv ("MONO_DISABLE_AIO") != NULL);
720 if (FALSE == data->epoll_disabled) {
721 data->epollfd = epoll_create (256);
722 data->epoll_disabled = (data->epollfd == -1);
723 if (data->epoll_disabled && g_getenv ("MONO_DEBUG"))
724 g_message ("epoll_create() failed. Using plain poll().");
729 data->epoll_disabled = TRUE;
733 if (data->epoll_disabled) {
734 if (pipe (data->pipe) != 0) {
744 srv = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
745 g_assert (srv != INVALID_SOCKET);
746 data->pipe [1] = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
747 g_assert (data->pipe [1] != INVALID_SOCKET);
749 server.sin_family = AF_INET;
750 server.sin_addr.s_addr = inet_addr ("127.0.0.1");
752 if (bind (srv, (SOCKADDR *) &server, sizeof (server))) {
753 g_print ("%d\n", WSAGetLastError ());
757 len = sizeof (server);
758 getsockname (srv, (SOCKADDR *) &server, &len);
760 mono_thread_create (mono_get_root_domain (), connect_hack, &server);
761 len = sizeof (server);
762 data->pipe [0] = accept (srv, (SOCKADDR *) &client, &len);
763 g_assert (data->pipe [0] != INVALID_SOCKET);
766 data->sock_to_state = mono_g_hash_table_new_type (g_direct_hash, g_direct_equal, MONO_HASH_VALUE_GC);
768 if (data->epoll_disabled) {
769 data->new_sem = CreateSemaphore (NULL, 1, 1, NULL);
770 g_assert (data->new_sem != NULL);
773 stack_size = mono_threads_get_default_stacksize ();
774 mono_threads_set_default_stacksize (128 * 1024);
775 if (data->epoll_disabled) {
776 mono_thread_create_internal (mono_get_root_domain (), socket_io_poll_main, data, TRUE);
780 mono_thread_create_internal (mono_get_root_domain (), socket_io_epoll_main, data, TRUE);
783 mono_threads_set_default_stacksize (stack_size);
784 LeaveCriticalSection (&data->io_lock);
789 socket_io_add_poll (MonoSocketAsyncResult *state)
794 SocketIOData *data = &socket_io_data;
797 if (mono_runtime_is_shutting_down () || data->inited == 3 || data->sock_to_state == NULL)
800 #if defined(PLATFORM_MACOSX) || defined(PLATFORM_BSD) || defined(HOST_WIN32) || defined(PLATFORM_SOLARIS)
801 /* select() for connect() does not work well on the Mac. Bug #75436. */
802 /* Bug #77637 for the BSD 6 case */
803 /* Bug #78888 for the Windows case */
804 if (state->operation == AIO_OP_CONNECT && state->blocking == TRUE) {
805 //FIXME: increment number of threads while this one is waiting?
806 threadpool_append_job (&async_io_tp, (MonoObject *) state);
810 WaitForSingleObject (data->new_sem, INFINITE);
811 if (data->newpfd == NULL)
812 data->newpfd = g_new0 (mono_pollfd, 1);
814 EnterCriticalSection (&data->io_lock);
815 if (data->sock_to_state == NULL) {
816 LeaveCriticalSection (&data->io_lock);
820 /* FIXME: 64 bit issue: handle can be a pointer on windows? */
821 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (state->handle));
823 list = mono_mlist_alloc ((MonoObject*)state);
825 list = mono_mlist_append (list, (MonoObject*)state);
828 events = get_events_from_list (list);
829 INIT_POLLFD (data->newpfd, GPOINTER_TO_INT (state->handle), events);
830 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (state->handle), list);
831 LeaveCriticalSection (&data->io_lock);
832 *msg = (char) state->operation;
834 w = write (data->pipe [1], msg, 1);
837 send ((SOCKET) data->pipe [1], msg, 1, 0);
843 socket_io_add_epoll (MonoSocketAsyncResult *state)
846 SocketIOData *data = &socket_io_data;
847 struct epoll_event event;
851 if (mono_runtime_is_shutting_down () || data->inited == 3 || data->sock_to_state == NULL)
854 memset (&event, 0, sizeof (struct epoll_event));
855 fd = GPOINTER_TO_INT (state->handle);
856 EnterCriticalSection (&data->io_lock);
857 if (data->sock_to_state == NULL) {
858 LeaveCriticalSection (&data->io_lock);
861 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
863 list = mono_mlist_alloc ((MonoObject*)state);
864 epoll_op = EPOLL_CTL_ADD;
866 list = mono_mlist_append (list, (MonoObject*)state);
867 epoll_op = EPOLL_CTL_MOD;
870 ievt = get_events_from_list (list);
871 if ((ievt & MONO_POLLIN) != 0)
872 event.events |= EPOLLIN;
873 if ((ievt & MONO_POLLOUT) != 0)
874 event.events |= EPOLLOUT;
876 mono_g_hash_table_replace (data->sock_to_state, state->handle, list);
878 EPOLL_DEBUG ("%s %d with %d", epoll_op == EPOLL_CTL_ADD ? "ADD" : "MOD", fd, event.events);
879 if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
881 if (epoll_op == EPOLL_CTL_ADD && err == EEXIST) {
882 epoll_op = EPOLL_CTL_MOD;
883 if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
884 g_message ("epoll_ctl(MOD): %d %s", err, g_strerror (err));
888 LeaveCriticalSection (&data->io_lock);
895 socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
897 if (async_tp.pool_status == 2 || mono_runtime_is_shutting_down ())
900 socket_io_init (&socket_io_data);
902 MONO_OBJECT_SETREF (state, ares, ares);
904 if (socket_io_data.epoll_disabled == FALSE) {
905 if (socket_io_add_epoll (state))
909 socket_io_add_poll (state);
912 #ifndef DISABLE_SOCKETS
914 socket_io_filter (MonoObject *target, MonoObject *state)
917 MonoSocketAsyncResult *sock_res = (MonoSocketAsyncResult *) state;
920 if (target == NULL || state == NULL)
923 if (socket_async_call_klass == NULL) {
924 klass = target->vtable->klass;
925 /* Check if it's SocketAsyncCall in System.Net.Sockets
926 * FIXME: check the assembly is signed correctly for extra care
928 if (klass->name [0] == 'S' && strcmp (klass->name, "SocketAsyncCall") == 0
929 && strcmp (mono_image_get_name (klass->image), "System") == 0
930 && klass->nested_in && strcmp (klass->nested_in->name, "Socket") == 0)
931 socket_async_call_klass = klass;
934 if (process_async_call_klass == NULL) {
935 klass = target->vtable->klass;
936 /* Check if it's AsyncReadHandler in System.Diagnostics.Process
937 * FIXME: check the assembly is signed correctly for extra care
939 if (klass->name [0] == 'A' && strcmp (klass->name, "AsyncReadHandler") == 0
940 && strcmp (mono_image_get_name (klass->image), "System") == 0
941 && klass->nested_in && strcmp (klass->nested_in->name, "Process") == 0)
942 process_async_call_klass = klass;
944 /* return both when socket_async_call_klass has not been seen yet and when
945 * the object is not an instance of the class.
947 if (target->vtable->klass != socket_async_call_klass && target->vtable->klass != process_async_call_klass)
950 op = sock_res->operation;
951 if (op < AIO_OP_FIRST || op >= AIO_OP_LAST)
956 #endif /* !DISABLE_SOCKETS */
958 /* Returns the exception thrown when invoking, if any */
960 mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares)
962 ASyncCall *ac = (ASyncCall *)ares->object_data;
963 MonoObject *res, *exc = NULL;
964 MonoArray *out_args = NULL;
965 HANDLE wait_event = NULL;
967 if (ares->execution_context) {
968 /* use captured ExecutionContext (if available) */
969 MONO_OBJECT_SETREF (ares, original_context, mono_thread_get_execution_context ());
970 mono_thread_set_execution_context (ares->execution_context);
972 ares->original_context = NULL;
976 /* Fast path from ThreadPool.*QueueUserWorkItem */
977 void *pa = ares->async_state;
978 mono_runtime_delegate_invoke (ares->async_delegate, &pa, &exc);
981 res = mono_message_invoke (ares->async_delegate, ac->msg, &exc, &out_args);
982 MONO_OBJECT_SETREF (ac, res, res);
983 MONO_OBJECT_SETREF (ac, msg->exc, exc);
984 MONO_OBJECT_SETREF (ac, out_args, out_args);
986 mono_monitor_enter ((MonoObject *) ares);
988 if (ares->handle != NULL)
989 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
990 mono_monitor_exit ((MonoObject *) ares);
991 /* notify listeners */
992 if (wait_event != NULL)
993 SetEvent (wait_event);
995 /* call async callback if cb_method != null*/
996 if (ac != NULL && ac->cb_method) {
997 MonoObject *exc = NULL;
999 mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &exc);
1000 /* 'exc' will be the previous ac->msg->exc if not NULL and not
1001 * catched. If catched, this will be set to NULL and the
1002 * exception will not be printed. */
1003 MONO_OBJECT_SETREF (ac->msg, exc, exc);
1007 /* restore original thread execution context if flow isn't suppressed, i.e. non null */
1008 if (ares->original_context) {
1009 mono_thread_set_execution_context (ares->original_context);
1010 ares->original_context = NULL;
1016 threadpool_start_idle_threads (ThreadPool *tp)
1023 if (n >= tp->min_threads)
1025 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n)
1028 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
1029 mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE);
1030 SleepEx (100, TRUE);
1035 threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer))
1037 memset (tp, 0, sizeof (ThreadPool));
1038 MONO_SEM_INIT (&tp->lock, 1);
1039 tp->min_threads = min_threads;
1040 tp->max_threads = max_threads;
1041 tp->async_invoke = async_invoke;
1042 MONO_SEM_INIT (&tp->new_job, 0);
1046 init_perf_counter (const char *category, const char *counter)
1048 MonoString *category_str;
1049 MonoString *counter_str;
1050 MonoString *machine;
1055 if (category == NULL || counter == NULL)
1057 root = mono_get_root_domain ();
1058 category_str = mono_string_new (root, category);
1059 counter_str = mono_string_new (root, counter);
1060 machine = mono_string_new (root, ".");
1061 return mono_perfcounter_get_impl (category_str, counter_str, NULL, machine, &type, &custom);
1066 print_pool_info (ThreadPool *tp)
1069 // if (tp->tail - tp->head == 0)
1072 g_print ("Pool status? %d\n", InterlockedCompareExchange (&tp->pool_status, 0, 0));
1073 g_print ("Min. threads: %d\n", InterlockedCompareExchange (&tp->min_threads, 0, 0));
1074 g_print ("Max. threads: %d\n", InterlockedCompareExchange (&tp->max_threads, 0, 0));
1075 g_print ("nthreads: %d\n", InterlockedCompareExchange (&tp->nthreads, 0, 0));
1076 g_print ("busy threads: %d\n", InterlockedCompareExchange (&tp->busy_threads, 0, 0));
1077 g_print ("Waiting: %d\n", InterlockedCompareExchange (&tp->waiting, 0, 0));
1078 g_print ("Queued: %d\n", (tp->tail - tp->head));
1079 if (tp == &async_tp) {
1081 EnterCriticalSection (&wsqs_lock);
1082 for (i = 0; i < wsqs->len; i++) {
1083 g_print ("\tWSQ %d: %d\n", i, mono_wsq_count (g_ptr_array_index (wsqs, i)));
1085 LeaveCriticalSection (&wsqs_lock);
1087 g_print ("\tSockets: %d\n", mono_g_hash_table_size (socket_io_data.sock_to_state));
1089 g_print ("-------------\n");
1093 signal_handler (int signo)
1098 MONO_SEM_WAIT (&tp->lock);
1099 g_print ("\n-----Non-IO-----\n");
1100 print_pool_info (tp);
1101 MONO_SEM_POST (&tp->lock);
1103 MONO_SEM_WAIT (&tp->lock);
1104 g_print ("\n-----IO-----\n");
1105 print_pool_info (tp);
1106 MONO_SEM_POST (&tp->lock);
1112 mono_thread_pool_init ()
1114 gint threads_per_cpu = 1;
1116 gint cpu_count = mono_cpu_count ();
1122 result = InterlockedCompareExchange (&tp_inited, 1, 0);
1131 MONO_GC_REGISTER_ROOT (async_tp.first);
1132 MONO_GC_REGISTER_ROOT (async_tp.last);
1133 MONO_GC_REGISTER_ROOT (async_tp.unused);
1134 MONO_GC_REGISTER_ROOT (async_io_tp.first);
1135 MONO_GC_REGISTER_ROOT (async_io_tp.unused);
1136 MONO_GC_REGISTER_ROOT (async_io_tp.last);
1138 MONO_GC_REGISTER_ROOT (socket_io_data.sock_to_state);
1139 InitializeCriticalSection (&socket_io_data.io_lock);
1140 if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
1141 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
1142 if (threads_per_cpu < 1)
1143 threads_per_cpu = 1;
1146 thread_count = MIN (cpu_count * threads_per_cpu, 100 * cpu_count);
1147 threadpool_init (&async_tp, thread_count, MAX (100 * cpu_count, thread_count), async_invoke_thread);
1148 threadpool_init (&async_io_tp, cpu_count * 2, cpu_count * 4, async_invoke_thread);
1149 async_io_tp.is_io = TRUE;
1151 async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
1152 g_assert (async_call_klass);
1154 InitializeCriticalSection (&wsqs_lock);
1155 wsqs = g_ptr_array_sized_new (MAX (100 * cpu_count, thread_count));
1158 async_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "Work Items Added");
1159 g_assert (async_tp.pc_nitems);
1161 async_io_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "IO Work Items Added");
1162 g_assert (async_io_tp.pc_nitems);
1164 async_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of Threads");
1165 g_assert (async_tp.pc_nthreads);
1167 async_io_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of IO Threads");
1168 g_assert (async_io_tp.pc_nthreads);
1171 signal (SIGALRM, signal_handler);
1177 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
1180 MonoDomain *domain = mono_domain_get ();
1181 MonoAsyncResult *ares;
1184 ac = (ASyncCall*)mono_object_new (domain, async_call_klass);
1185 MONO_OBJECT_SETREF (ac, msg, msg);
1186 MONO_OBJECT_SETREF (ac, state, state);
1188 if (async_callback) {
1189 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
1190 MONO_OBJECT_SETREF (ac, cb_target, async_callback);
1193 ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
1194 MONO_OBJECT_SETREF (ares, async_delegate, target);
1196 #ifndef DISABLE_SOCKETS
1197 if (socket_io_filter (target, state)) {
1198 socket_io_add (ares, (MonoSocketAsyncResult *) state);
1202 threadpool_append_job (&async_tp, (MonoObject *) ares);
1207 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1215 /* check if already finished */
1216 mono_monitor_enter ((MonoObject *) ares);
1218 if (ares->endinvoke_called) {
1219 *exc = (MonoObject *) mono_get_exception_invalid_operation (NULL);
1220 mono_monitor_exit ((MonoObject *) ares);
1224 ares->endinvoke_called = 1;
1225 /* wait until we are really finished */
1226 if (!ares->completed) {
1227 if (ares->handle == NULL) {
1228 wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1229 g_assert(wait_event != 0);
1230 MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), wait_event));
1232 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
1234 mono_monitor_exit ((MonoObject *) ares);
1235 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
1237 mono_monitor_exit ((MonoObject *) ares);
1240 ac = (ASyncCall *) ares->object_data;
1241 g_assert (ac != NULL);
1242 *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1243 *out_args = ac->out_args;
1249 threadpool_kill_idle_threads (ThreadPool *tp)
1253 n = (gint) InterlockedCompareExchange (&tp->max_threads, 0, -1);
1256 MONO_SEM_POST (&tp->new_job);
1261 mono_thread_pool_cleanup (void)
1263 if (async_tp.pool_status == 0 || async_tp.pool_status == 2)
1266 if (async_tp.pool_status == 1 && InterlockedCompareExchange (&async_tp.pool_status, 2, 1) == 2)
1269 InterlockedExchange (&async_io_tp.pool_status, 2);
1270 MONO_SEM_WAIT (&async_tp.lock);
1271 threadpool_free_queue (&async_tp);
1272 threadpool_kill_idle_threads (&async_tp);
1273 MONO_SEM_POST (&async_tp.lock);
1275 socket_io_cleanup (&socket_io_data); /* Empty when DISABLE_SOCKETS is defined */
1276 MONO_SEM_WAIT (&async_io_tp.lock);
1277 threadpool_free_queue (&async_io_tp);
1278 threadpool_kill_idle_threads (&async_io_tp);
1279 MONO_SEM_POST (&async_io_tp.lock);
1280 MONO_SEM_DESTROY (&async_io_tp.new_job);
1282 EnterCriticalSection (&wsqs_lock);
1283 mono_wsq_cleanup ();
1285 g_ptr_array_free (wsqs, TRUE);
1287 LeaveCriticalSection (&wsqs_lock);
1288 MONO_SEM_DESTROY (&async_tp.new_job);
1291 /* Caller must enter &tp->lock */
1293 dequeue_job_nolock (ThreadPool *tp)
1301 if (mono_runtime_is_shutting_down ())
1303 if (!list || tp->head == tp->tail)
1306 array = (MonoArray *) mono_mlist_get_data (list);
1307 ar = mono_array_get (array, MonoObject *, tp->head % QUEUE_LENGTH);
1308 mono_array_set (array, MonoObject *, tp->head % QUEUE_LENGTH, NULL);
1310 if ((tp->head % QUEUE_LENGTH) == 0) {
1312 tp->first = mono_mlist_next (list);
1313 if (tp->first == NULL)
1315 if (mono_mlist_length (tp->unused) < 20) {
1316 /* reuse this chunk */
1317 tp->unused = mono_mlist_set_next (list, tp->unused);
1319 tp->head -= QUEUE_LENGTH;
1320 tp->tail -= QUEUE_LENGTH;
1323 } while (ar == NULL);
1328 threadpool_start_thread (ThreadPool *tp)
1332 while (!mono_runtime_is_shutting_down () && (n = tp->nthreads) < tp->max_threads) {
1333 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n) {
1334 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
1335 mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE);
1344 pulse_on_new_job (ThreadPool *tp)
1347 MONO_SEM_POST (&tp->new_job);
1351 icall_append_job (MonoObject *ar)
1353 threadpool_append_job (&async_tp, ar);
1357 threadpool_append_job (ThreadPool *tp, MonoObject *ar)
1359 threadpool_append_jobs (tp, &ar, 1);
1363 create_or_reuse_list (ThreadPool *tp)
1371 tp->unused = mono_mlist_next (list);
1372 mono_mlist_set_next (list, NULL);
1373 //TP_DEBUG (tp->nodes_reused++);
1375 array = mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, QUEUE_LENGTH);
1376 list = mono_mlist_alloc ((MonoObject *) array);
1377 //TP_DEBUG (tp->nodes_created++);
1383 threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs)
1385 static int job_counter;
1390 gboolean lock_taken = FALSE; /* We won't take the lock when the local queue is used */
1392 if (mono_runtime_is_shutting_down ())
1395 if (tp->pool_status == 0 && InterlockedCompareExchange (&tp->pool_status, 1, 0) == 0)
1396 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, tp, TRUE);
1398 for (i = 0; i < njobs; i++) {
1400 if (ar == NULL || mono_domain_is_unloading (ar->vtable->domain))
1401 continue; /* Might happen when cleaning domain jobs */
1402 if (!tp->is_io && (InterlockedIncrement (&job_counter) % 10) == 0) {
1403 MonoAsyncResult *o = (MonoAsyncResult *) ar;
1404 o->add_time = mono_100ns_ticks ();
1406 threadpool_jobs_inc (ar);
1407 mono_perfcounter_update_value (tp->pc_nitems, TRUE, 1);
1408 if (!tp->is_io && mono_wsq_local_push (ar))
1412 MONO_SEM_WAIT (&tp->lock);
1415 if ((tp->tail % QUEUE_LENGTH) == 0) {
1416 list = create_or_reuse_list (tp);
1417 if (tp->last != NULL)
1418 mono_mlist_set_next (tp->last, list);
1420 if (tp->first == NULL)
1421 tp->first = tp->last;
1424 array = (MonoArray *) mono_mlist_get_data (tp->last);
1425 mono_array_setref (array, tp->tail % QUEUE_LENGTH, ar);
1429 MONO_SEM_POST (&tp->lock);
1431 if (!tp->is_io && tp->waiting == 0) {
1432 gint64 ticks = mono_100ns_ticks ();
1434 if (tp->last_check == 0 || (ticks - tp->last_check) > 5000000) {
1435 SPIN_LOCK (tp->sp_lock);
1436 tp->last_check = ticks;
1437 SPIN_UNLOCK (tp->sp_lock);
1438 threadpool_start_thread (tp);
1441 for (i = 0; i < MIN(njobs, tp->max_threads); i++)
1442 pulse_on_new_job (tp);
1446 threadpool_clear_queue (ThreadPool *tp, MonoDomain *domain)
1455 MONO_SEM_WAIT (&tp->lock);
1456 current = tp->first;
1458 array = (MonoArray *) mono_mlist_get_data (current);
1459 for (i = 0; i < QUEUE_LENGTH; i++) {
1460 obj = mono_array_get (array, MonoObject*, i);
1461 if (obj != NULL && obj->vtable->domain == domain) {
1463 mono_array_setref (array, i, NULL);
1464 threadpool_jobs_dec (obj);
1467 current = mono_mlist_next (current);
1470 if (!domain_count) {
1471 MONO_SEM_POST (&tp->lock);
1475 current = tp->first;
1480 MONO_SEM_POST (&tp->lock);
1481 /* Re-add everything but the nullified elements */
1483 array = (MonoArray *) mono_mlist_get_data (current);
1484 threadpool_append_jobs (tp, mono_array_addr (array, MonoObject *, 0), QUEUE_LENGTH);
1485 memset (mono_array_addr (array, MonoObject *, 0), 0, sizeof (MonoObject *) * QUEUE_LENGTH);
1486 current = mono_mlist_next (current);
1491 * Clean up the threadpool of all domain jobs.
1492 * Can only be called as part of the domain unloading process as
1493 * it will wait for all jobs to be visible to the interruption code.
1496 mono_thread_pool_remove_domain_jobs (MonoDomain *domain, int timeout)
1500 guint32 start_time = 0;
1502 g_assert (domain->state == MONO_APPDOMAIN_UNLOADING);
1504 threadpool_clear_queue (&async_tp, domain);
1505 threadpool_clear_queue (&async_io_tp, domain);
1508 * There might be some threads out that could be about to execute stuff from the given domain.
1509 * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
1511 sem_handle = CreateSemaphore (NULL, 0, 1, NULL);
1513 domain->cleanup_semaphore = sem_handle;
1515 * The memory barrier here is required to have global ordering between assigning to cleanup_semaphone
1516 * and reading threadpool_jobs.
1517 * Otherwise this thread could read a stale version of threadpool_jobs and wait forever.
1519 mono_memory_write_barrier ();
1521 if (domain->threadpool_jobs && timeout != -1)
1522 start_time = mono_msec_ticks ();
1523 while (domain->threadpool_jobs) {
1524 WaitForSingleObject (sem_handle, timeout);
1525 if (timeout != -1 && (mono_msec_ticks () - start_time) > timeout) {
1531 domain->cleanup_semaphore = NULL;
1532 CloseHandle (sem_handle);
1537 threadpool_free_queue (ThreadPool *tp)
1539 tp->head = tp->tail = 0;
1545 mono_thread_pool_is_queue_array (MonoArray *o)
1549 // FIXME: need some fix in sgen code.
1550 // There are roots at: async*tp.unused (MonoMList) and wsqs [n]->queue (MonoArray)
1551 return obj == async_tp.first || obj == async_io_tp.first;
1555 add_wsq (MonoWSQ *wsq)
1562 EnterCriticalSection (&wsqs_lock);
1564 LeaveCriticalSection (&wsqs_lock);
1567 for (i = 0; i < wsqs->len; i++) {
1568 if (g_ptr_array_index (wsqs, i) == NULL) {
1569 wsqs->pdata [i] = wsq;
1570 LeaveCriticalSection (&wsqs_lock);
1574 g_ptr_array_add (wsqs, wsq);
1575 LeaveCriticalSection (&wsqs_lock);
1579 remove_wsq (MonoWSQ *wsq)
1584 EnterCriticalSection (&wsqs_lock);
1586 LeaveCriticalSection (&wsqs_lock);
1589 g_ptr_array_remove_fast (wsqs, wsq);
1590 LeaveCriticalSection (&wsqs_lock);
1594 try_steal (gpointer *data, gboolean retry)
1599 if (wsqs == NULL || data == NULL || *data != NULL)
1604 if (mono_runtime_is_shutting_down ())
1606 for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
1607 if (mono_runtime_is_shutting_down ()) {
1610 mono_wsq_try_steal (wsqs->pdata [i], data, ms);
1611 if (*data != NULL) {
1616 } while (retry && ms < 11);
1620 dequeue_or_steal (ThreadPool *tp, gpointer *data)
1622 if (mono_runtime_is_shutting_down ())
1624 TP_DEBUG ("Dequeue");
1625 MONO_SEM_WAIT (&tp->lock);
1626 *data = dequeue_job_nolock (tp);
1627 MONO_SEM_POST (&tp->lock);
1628 if (!tp->is_io && !*data)
1629 try_steal (data, FALSE);
1630 return (*data != NULL);
1634 process_idle_times (ThreadPool *tp, gint64 t)
1638 gboolean compute_avg;
1642 if (tp->ignore_times || t <= 0)
1645 compute_avg = FALSE;
1646 ticks = mono_100ns_ticks ();
1648 SPIN_LOCK (tp->sp_lock);
1649 if (tp->ignore_times) {
1650 SPIN_UNLOCK (tp->sp_lock);
1655 if (tp->last_check == 0)
1656 tp->last_check = ticks;
1657 else if (tp->last_check > 0 && (ticks - tp->last_check) > 5000000) {
1658 tp->ignore_times = 1;
1661 SPIN_UNLOCK (tp->sp_lock);
1666 //printf ("Items: %d Time elapsed: %.3fs\n", tp->n_sum, (ticks - tp->last_check) / 10000.0);
1667 tp->last_check = ticks;
1669 avg = tp->time_sum / tp->n_sum;
1670 if (tp->averages [1] == 0) {
1671 tp->averages [1] = avg;
1673 per1 = ((100 * (ABS (avg - tp->averages [1]))) / tp->averages [1]);
1675 if (avg > tp->averages [1]) {
1676 if (tp->averages [1] < tp->averages [0]) {
1681 } else if (avg < tp->averages [1] && tp->averages [1] < tp->averages [0]) {
1686 min = tp->min_threads;
1688 if ((n - min) < min && tp->busy_threads == n)
1692 if (new_threads != 0) {
1693 printf ("n: %d per1: %lld avg=%lld avg1=%lld avg0=%lld\n", new_threads, per1, avg, tp->averages [1], tp->averages [0]);
1701 tp->averages [0] = tp->averages [1];
1702 tp->averages [1] = avg;
1703 tp->ignore_times = 0;
1705 if (tp->waiting == 0 && new_threads == 1) {
1706 threadpool_start_thread (tp);
1707 } else if (new_threads == -1) {
1708 if (tp->destroy_thread == 0 && InterlockedCompareExchange (&tp->destroy_thread, 1, 0) == 0)
1709 pulse_on_new_job (tp);
1714 should_i_die (ThreadPool *tp)
1716 gboolean result = FALSE;
1717 if (tp->destroy_thread == 1 && InterlockedCompareExchange (&tp->destroy_thread, 0, 1) == 1)
1718 result = (tp->nthreads > tp->min_threads);
1723 async_invoke_thread (gpointer data)
1726 MonoInternalThread *thread;
1734 wsq = mono_wsq_create ();
1738 thread = mono_thread_internal_current ();
1740 tp_start_func (tp_hooks_user_data);
1743 MonoAsyncResult *ar;
1744 gboolean is_io_task;
1748 ar = (MonoAsyncResult *) data;
1750 InterlockedIncrement (&tp->busy_threads);
1751 #ifndef DISABLE_SOCKETS
1752 is_io_task = (strcmp (((MonoObject *) data)->vtable->klass->name, "AsyncResult"));
1754 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1756 switch (state->operation) {
1757 case AIO_OP_RECEIVE:
1758 state->total = ICALL_RECV (state);
1761 state->total = ICALL_SEND (state);
1766 /* worker threads invokes methods in different domains,
1767 * so we need to set the right domain here */
1768 domain = ((MonoObject *)ar)->vtable->domain;
1771 if (mono_domain_is_unloading (domain) || mono_runtime_is_shutting_down ()) {
1772 threadpool_jobs_dec ((MonoObject *)ar);
1775 InterlockedDecrement (&tp->busy_threads);
1777 mono_thread_push_appdomain_ref (domain);
1778 if (threadpool_jobs_dec ((MonoObject *)ar)) {
1781 mono_thread_pop_appdomain_ref ();
1782 InterlockedDecrement (&tp->busy_threads);
1786 if (mono_domain_set (domain, FALSE)) {
1787 /* ASyncCall *ac; */
1789 if (tp_item_begin_func)
1790 tp_item_begin_func (tp_item_user_data);
1792 if (!is_io_task && ar->add_time > 0)
1793 process_idle_times (tp, ar->add_time);
1794 /*FIXME: Do something with the exception returned? */
1795 mono_async_invoke (tp, ar);
1796 if (tp_item_end_func)
1797 tp_item_end_func (tp_item_user_data);
1799 ac = (ASyncCall *) ar->object_data;
1800 if (ac->msg->exc != NULL)
1801 mono_unhandled_exception (ac->msg->exc);
1803 mono_domain_set (mono_get_root_domain (), TRUE);
1805 mono_thread_pop_appdomain_ref ();
1806 InterlockedDecrement (&tp->busy_threads);
1807 /* If the callee changes the background status, set it back to TRUE */
1808 if (!mono_thread_test_state (thread , ThreadState_Background))
1809 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
1815 must_die = should_i_die (tp);
1816 TP_DEBUG ("Trying to get a job");
1817 if (!must_die && (tp->is_io || !mono_wsq_local_pop (&data)))
1818 dequeue_or_steal (tp, &data);
1819 TP_DEBUG ("Done trying to get a job %p", data);
1822 while (!must_die && !data && n_naps < 4) {
1825 TP_DEBUG ("Waiting");
1826 InterlockedIncrement (&tp->waiting);
1827 #if defined(__OpenBSD__)
1828 while ((res = mono_sem_wait (&tp->new_job, TRUE)) == -1) {// && errno == EINTR) {
1830 while ((res = mono_sem_timedwait (&tp->new_job, 2000, TRUE)) == -1) {// && errno == EINTR) {
1832 if (mono_runtime_is_shutting_down ())
1834 if (THREAD_WANTS_A_BREAK (thread))
1835 mono_thread_interruption_checkpoint ();
1837 TP_DEBUG ("Done waiting");
1838 InterlockedDecrement (&tp->waiting);
1839 if (mono_runtime_is_shutting_down ())
1841 must_die = should_i_die (tp);
1842 dequeue_or_steal (tp, &data);
1846 if (!data && tp->is_io && !mono_runtime_is_shutting_down ()) {
1847 mono_wsq_local_pop (&data);
1848 if (data && must_die) {
1849 InterlockedCompareExchange (&tp->destroy_thread, 1, 0);
1850 pulse_on_new_job (tp);
1859 down = mono_runtime_is_shutting_down ();
1860 if (!down && nt <= tp->min_threads)
1862 if (down || InterlockedCompareExchange (&tp->nthreads, nt - 1, nt) == nt) {
1863 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, -1);
1867 while (mono_wsq_local_pop (&data)) {
1868 threadpool_jobs_dec (data);
1871 mono_wsq_destroy (wsq);
1874 tp_finish_func (tp_hooks_user_data);
1881 g_assert_not_reached ();
1885 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
1887 *workerThreads = async_tp.max_threads - async_tp.busy_threads;
1888 *completionPortThreads = async_io_tp.max_threads - async_io_tp.busy_threads;
1892 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
1894 *workerThreads = async_tp.max_threads;
1895 *completionPortThreads = async_io_tp.max_threads;
1899 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
1901 *workerThreads = async_tp.min_threads;
1902 *completionPortThreads = async_io_tp.min_threads;
1906 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
1909 gint max_io_threads;
1911 max_threads = async_tp.max_threads;
1912 if (workerThreads <= 0 || workerThreads > max_threads)
1915 max_io_threads = async_io_tp.max_threads;
1916 if (completionPortThreads <= 0 || completionPortThreads > max_io_threads)
1919 InterlockedExchange (&async_tp.min_threads, workerThreads);
1920 InterlockedExchange (&async_io_tp.min_threads, completionPortThreads);
1921 if (workerThreads > async_tp.nthreads)
1922 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_tp, TRUE);
1923 if (completionPortThreads > async_io_tp.nthreads)
1924 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_io_tp, TRUE);
1929 ves_icall_System_Threading_ThreadPool_SetMaxThreads (gint workerThreads, gint completionPortThreads)
1932 gint min_io_threads;
1935 cpu_count = mono_cpu_count ();
1936 min_threads = async_tp.min_threads;
1937 if (workerThreads < min_threads || workerThreads < cpu_count)
1940 /* We don't really have the concept of completion ports. Do we care here? */
1941 min_io_threads = async_io_tp.min_threads;
1942 if (completionPortThreads < min_io_threads || completionPortThreads < cpu_count)
1945 InterlockedExchange (&async_tp.max_threads, workerThreads);
1946 InterlockedExchange (&async_io_tp.max_threads, completionPortThreads);
1951 * mono_install_threadpool_thread_hooks
1952 * @start_func: the function to be called right after a new threadpool thread is created. Can be NULL.
1953 * @finish_func: the function to be called right before a thredpool thread is exiting. Can be NULL.
1954 * @user_data: argument passed to @start_func and @finish_func.
1956 * @start_fun will be called right after a threadpool thread is created and @finish_func right before a threadpool thread exits.
1957 * The calls will be made from the thread itself.
1960 mono_install_threadpool_thread_hooks (MonoThreadPoolFunc start_func, MonoThreadPoolFunc finish_func, gpointer user_data)
1962 tp_start_func = start_func;
1963 tp_finish_func = finish_func;
1964 tp_hooks_user_data = user_data;
1968 * mono_install_threadpool_item_hooks
1969 * @begin_func: the function to be called before a threadpool work item processing starts.
1970 * @end_func: the function to be called after a threadpool work item is finished.
1971 * @user_data: argument passed to @begin_func and @end_func.
1973 * The calls will be made from the thread itself and from the same AppDomain
1974 * where the work item was executed.
1978 mono_install_threadpool_item_hooks (MonoThreadPoolItemFunc begin_func, MonoThreadPoolItemFunc end_func, gpointer user_data)
1980 tp_item_begin_func = begin_func;
1981 tp_item_end_func = end_func;
1982 tp_item_user_data = user_data;