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);
177 static gboolean threadpool_start_thread (ThreadPool *tp);
178 static void monitor_thread (gpointer data);
180 static MonoClass *async_call_klass;
181 static MonoClass *socket_async_call_klass;
182 static MonoClass *process_async_call_klass;
184 static GPtrArray *wsqs;
185 CRITICAL_SECTION wsqs_lock;
188 static MonoThreadPoolFunc tp_start_func;
189 static MonoThreadPoolFunc tp_finish_func;
190 static gpointer tp_hooks_user_data;
191 static MonoThreadPoolItemFunc tp_item_begin_func;
192 static MonoThreadPoolItemFunc tp_item_end_func;
193 static gpointer tp_item_user_data;
195 #define INIT_POLLFD(a, b, c) {(a)->fd = b; (a)->events = c; (a)->revents = 0;}
204 AIO_OP_RECV_JUST_CALLBACK,
205 AIO_OP_SEND_JUST_CALLBACK,
209 AIO_OP_ACCEPTRECEIVE,
210 AIO_OP_RECEIVE_BUFFERS,
215 #ifdef DISABLE_SOCKETS
217 #define socket_io_cleanup(x)
220 get_event_from_state (MonoSocketAsyncResult *state)
222 g_assert_not_reached ();
227 get_events_from_list (MonoMList *list)
235 socket_io_cleanup (SocketIOData *data)
237 EnterCriticalSection (&data->io_lock);
238 if (data->inited != 2) {
239 LeaveCriticalSection (&data->io_lock);
245 closesocket (data->pipe [0]);
246 closesocket (data->pipe [1]);
248 if (data->pipe [0] > -1)
249 close (data->pipe [0]);
250 if (data->pipe [1] > -1)
251 close (data->pipe [1]);
256 CloseHandle (data->new_sem);
257 data->new_sem = NULL;
258 mono_g_hash_table_destroy (data->sock_to_state);
259 data->sock_to_state = NULL;
260 g_free (data->newpfd);
263 if (FALSE == data->epoll_disabled)
264 close (data->epollfd);
266 LeaveCriticalSection (&data->io_lock);
270 get_event_from_state (MonoSocketAsyncResult *state)
272 switch (state->operation) {
275 case AIO_OP_RECV_JUST_CALLBACK:
276 case AIO_OP_RECEIVEFROM:
277 case AIO_OP_READPIPE:
278 case AIO_OP_ACCEPTRECEIVE:
279 case AIO_OP_RECEIVE_BUFFERS:
282 case AIO_OP_SEND_JUST_CALLBACK:
285 case AIO_OP_SEND_BUFFERS:
286 case AIO_OP_DISCONNECT:
288 default: /* Should never happen */
289 g_message ("get_event_from_state: unknown value in switch!!!");
295 get_events_from_list (MonoMList *list)
297 MonoSocketAsyncResult *state;
300 while (list && (state = (MonoSocketAsyncResult *)mono_mlist_get_data (list))) {
301 events |= get_event_from_state (state);
302 list = mono_mlist_next (list);
308 #define ICALL_RECV(x) ves_icall_System_Net_Sockets_Socket_Receive_internal (\
309 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
310 x->socket_flags, &x->error);
312 #define ICALL_SEND(x) ves_icall_System_Net_Sockets_Socket_Send_internal (\
313 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
314 x->socket_flags, &x->error);
316 #endif /* !DISABLE_SOCKETS */
319 threadpool_jobs_inc (MonoObject *obj)
322 InterlockedIncrement (&obj->vtable->domain->threadpool_jobs);
326 threadpool_jobs_dec (MonoObject *obj)
328 MonoDomain *domain = obj->vtable->domain;
329 int remaining_jobs = InterlockedDecrement (&domain->threadpool_jobs);
330 if (remaining_jobs == 0 && domain->cleanup_semaphore) {
331 ReleaseSemaphore (domain->cleanup_semaphore, 1, NULL);
339 get_io_event (MonoMList **list, gint event)
349 state = mono_mlist_get_data (current);
350 if (get_event_from_state ((MonoSocketAsyncResult *) state) == event)
355 current = mono_mlist_next (current);
360 mono_mlist_set_next (prev, mono_mlist_next (current));
362 *list = mono_mlist_next (*list);
371 process_io_event (MonoMList *list, int event)
373 MonoSocketAsyncResult *state;
379 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
380 if (get_event_from_state (state) == event)
383 list = mono_mlist_next (list);
387 oldlist = mono_mlist_remove_item (oldlist, list);
388 EPOLL_DEBUG ("Dispatching event %d on socket %p", event, state->handle);
389 threadpool_append_job (&async_io_tp, (MonoObject *) state);
396 mark_bad_fds (mono_pollfd *pfds, int nfds)
402 for (i = 0; i < nfds; i++) {
407 ret = mono_poll (pfd, 1, 0);
408 if (ret == -1 && errno == EBADF) {
409 pfd->revents |= MONO_POLLNVAL;
411 } else if (ret == 1) {
420 socket_io_poll_main (gpointer p)
422 #if MONO_SMALL_CONFIG
423 #define INITIAL_POLLFD_SIZE 128
425 #define INITIAL_POLLFD_SIZE 1024
427 #define POLL_ERRORS (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL)
428 SocketIOData *data = p;
433 MonoInternalThread *thread;
435 thread = mono_thread_internal_current ();
437 allocated = INITIAL_POLLFD_SIZE;
438 pfds = g_new0 (mono_pollfd, allocated);
439 INIT_POLLFD (pfds, data->pipe [0], MONO_POLLIN);
440 for (i = 1; i < allocated; i++)
441 INIT_POLLFD (&pfds [i], -1, 0);
451 if (THREAD_WANTS_A_BREAK (thread))
452 mono_thread_interruption_checkpoint ();
455 nsock = mono_poll (pfds, maxfd, -1);
456 } while (nsock == -1 && errno == EINTR);
459 * Apart from EINTR, we only check EBADF, for the rest:
460 * EINVAL: mono_poll() 'protects' us from descriptor
461 * numbers above the limit if using select() by marking
462 * then as MONO_POLLERR. If a system poll() is being
463 * used, the number of descriptor we're passing will not
464 * be over sysconf(_SC_OPEN_MAX), as the error would have
465 * happened when opening.
467 * EFAULT: we own the memory pointed by pfds.
468 * ENOMEM: we're doomed anyway
472 if (nsock == -1 && errno == EBADF) {
473 pfds->revents = 0; /* Just in case... */
474 nsock = mark_bad_fds (pfds, maxfd);
477 if ((pfds->revents & POLL_ERRORS) != 0) {
478 /* We're supposed to die now, as the pipe has been closed */
480 socket_io_cleanup (data);
484 /* Got a new socket */
485 if ((pfds->revents & MONO_POLLIN) != 0) {
488 for (i = 1; i < allocated; i++) {
490 if (pfd->fd == -1 || data->newpfd == NULL ||
491 pfd->fd == data->newpfd->fd)
495 if (i == allocated) {
500 allocated = allocated * 2;
501 pfds = g_renew (mono_pollfd, oldfd, allocated);
503 for (; i < allocated; i++)
504 INIT_POLLFD (&pfds [i], -1, 0);
507 nread = read (data->pipe [0], one, 1);
509 nread = recv ((SOCKET) data->pipe [0], one, 1, 0);
513 return; /* we're closed */
516 INIT_POLLFD (&pfds [i], data->newpfd->fd, data->newpfd->events);
517 ReleaseSemaphore (data->new_sem, 1, NULL);
526 EnterCriticalSection (&data->io_lock);
527 if (data->inited == 3) {
529 LeaveCriticalSection (&data->io_lock);
530 return; /* cleanup called */
533 for (i = 1; i < maxfd && nsock > 0; i++) {
535 if (pfd->fd == -1 || pfd->revents == 0)
539 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
540 if (list != NULL && (pfd->revents & (MONO_POLLIN | POLL_ERRORS)) != 0) {
541 list = process_io_event (list, MONO_POLLIN);
544 if (list != NULL && (pfd->revents & (MONO_POLLOUT | POLL_ERRORS)) != 0) {
545 list = process_io_event (list, MONO_POLLOUT);
549 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (pfd->fd), list);
550 pfd->events = get_events_from_list (list);
552 mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
558 LeaveCriticalSection (&data->io_lock);
563 #define EPOLL_ERRORS (EPOLLERR | EPOLLHUP)
564 #define EPOLL_NEVENTS 128
566 socket_io_epoll_main (gpointer p)
570 MonoInternalThread *thread;
571 struct epoll_event *events, *evt;
573 gpointer async_results [EPOLL_NEVENTS * 2]; // * 2 because each loop can add up to 2 results here
577 epollfd = data->epollfd;
578 thread = mono_thread_internal_current ();
579 events = g_new0 (struct epoll_event, EPOLL_NEVENTS);
584 if (THREAD_WANTS_A_BREAK (thread))
585 mono_thread_interruption_checkpoint ();
587 EPOLL_DEBUG ("epoll_wait init");
588 ready = epoll_wait (epollfd, events, EPOLL_NEVENTS, -1);
591 EPOLL_DEBUG ("epoll_wait end with %d ready sockets (%d %s).", ready, err, (ready == -1) ? g_strerror (err) : "");
594 } while (ready == -1 && errno == EINTR);
600 g_warning ("epoll_wait: %d %s", err, g_strerror (err));
606 EnterCriticalSection (&data->io_lock);
607 if (data->inited == 3) {
610 LeaveCriticalSection (&data->io_lock);
611 return; /* cleanup called */
615 for (i = 0; i < ready; i++) {
622 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
623 EPOLL_DEBUG ("Event %d on %d list length: %d", evt->events, fd, mono_mlist_length (list));
624 if (list != NULL && (evt->events & (EPOLLIN | EPOLL_ERRORS)) != 0) {
625 ares = get_io_event (&list, MONO_POLLIN);
627 async_results [nresults++] = ares;
630 if (list != NULL && (evt->events & (EPOLLOUT | EPOLL_ERRORS)) != 0) {
631 ares = get_io_event (&list, MONO_POLLOUT);
633 async_results [nresults++] = ares;
637 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (fd), list);
638 evt->events = get_events_from_list (list);
639 EPOLL_DEBUG ("MOD %d to %d", fd, evt->events);
640 if (epoll_ctl (epollfd, EPOLL_CTL_MOD, fd, evt)) {
641 if (epoll_ctl (epollfd, EPOLL_CTL_ADD, fd, evt) == -1) {
644 EPOLL_DEBUG ("epoll_ctl(MOD): %d %s fd: %d events: %d", err, g_strerror (err), fd, evt->events);
650 mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (fd));
651 EPOLL_DEBUG ("DEL %d", fd);
652 epoll_ctl (epollfd, EPOLL_CTL_DEL, fd, evt);
655 LeaveCriticalSection (&data->io_lock);
656 threadpool_append_jobs (&async_io_tp, (MonoObject **) async_results, nresults);
657 memset (async_results, 0, sizeof (gpointer) * nresults);
664 * select/poll wake up when a socket is closed, but epoll just removes
665 * the socket from its internal list without notification.
668 mono_thread_pool_remove_socket (int sock)
670 MonoMList *list, *next;
671 MonoSocketAsyncResult *state;
673 if (socket_io_data.inited == 0)
676 EnterCriticalSection (&socket_io_data.io_lock);
677 if (socket_io_data.sock_to_state == NULL) {
678 LeaveCriticalSection (&socket_io_data.io_lock);
681 list = mono_g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
683 mono_g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
684 LeaveCriticalSection (&socket_io_data.io_lock);
687 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
688 if (state->operation == AIO_OP_RECEIVE)
689 state->operation = AIO_OP_RECV_JUST_CALLBACK;
690 else if (state->operation == AIO_OP_SEND)
691 state->operation = AIO_OP_SEND_JUST_CALLBACK;
693 next = mono_mlist_remove_item (list, list);
694 list = process_io_event (list, MONO_POLLIN);
696 process_io_event (list, MONO_POLLOUT);
704 connect_hack (gpointer x)
706 struct sockaddr_in *addr = (struct sockaddr_in *) x;
709 while (connect ((SOCKET) socket_io_data.pipe [1], (SOCKADDR *) addr, sizeof (struct sockaddr_in))) {
712 g_warning ("Error initializing async. sockets %d.", WSAGetLastError ());
713 g_assert (WSAGetLastError ());
720 socket_io_init (SocketIOData *data)
723 struct sockaddr_in server;
724 struct sockaddr_in client;
731 if (data->inited >= 2) // 2 -> initialized, 3-> cleaned up
734 inited = InterlockedCompareExchange (&data->inited, 1, 0);
737 if (data->inited >= 2)
743 EnterCriticalSection (&data->io_lock);
746 data->epoll_disabled = (g_getenv ("MONO_DISABLE_AIO") != NULL);
747 if (FALSE == data->epoll_disabled) {
748 data->epollfd = epoll_create (256);
749 data->epoll_disabled = (data->epollfd == -1);
750 if (data->epoll_disabled && g_getenv ("MONO_DEBUG"))
751 g_message ("epoll_create() failed. Using plain poll().");
756 data->epoll_disabled = TRUE;
760 if (data->epoll_disabled) {
761 if (pipe (data->pipe) != 0) {
771 srv = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
772 g_assert (srv != INVALID_SOCKET);
773 data->pipe [1] = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
774 g_assert (data->pipe [1] != INVALID_SOCKET);
776 server.sin_family = AF_INET;
777 server.sin_addr.s_addr = inet_addr ("127.0.0.1");
779 if (bind (srv, (SOCKADDR *) &server, sizeof (server))) {
780 g_print ("%d\n", WSAGetLastError ());
784 len = sizeof (server);
785 getsockname (srv, (SOCKADDR *) &server, &len);
787 mono_thread_create (mono_get_root_domain (), connect_hack, &server);
788 len = sizeof (server);
789 data->pipe [0] = accept (srv, (SOCKADDR *) &client, &len);
790 g_assert (data->pipe [0] != INVALID_SOCKET);
793 data->sock_to_state = mono_g_hash_table_new_type (g_direct_hash, g_direct_equal, MONO_HASH_VALUE_GC);
795 if (data->epoll_disabled) {
796 data->new_sem = CreateSemaphore (NULL, 1, 1, NULL);
797 g_assert (data->new_sem != NULL);
800 stack_size = mono_threads_get_default_stacksize ();
801 /* 128k stacks could lead to problems on 64 bit systems with large pagesizes+altstack */
802 mono_threads_set_default_stacksize (128 * (sizeof (gpointer) / 4) * 1024);
803 if (data->epoll_disabled) {
804 mono_thread_create_internal (mono_get_root_domain (), socket_io_poll_main, data, TRUE);
808 mono_thread_create_internal (mono_get_root_domain (), socket_io_epoll_main, data, TRUE);
811 mono_threads_set_default_stacksize (stack_size);
812 LeaveCriticalSection (&data->io_lock);
817 socket_io_add_poll (MonoSocketAsyncResult *state)
822 SocketIOData *data = &socket_io_data;
825 if (mono_runtime_is_shutting_down () || data->inited == 3 || data->sock_to_state == NULL)
828 #if defined(PLATFORM_MACOSX) || defined(PLATFORM_BSD) || defined(HOST_WIN32) || defined(PLATFORM_SOLARIS)
829 /* select() for connect() does not work well on the Mac. Bug #75436. */
830 /* Bug #77637 for the BSD 6 case */
831 /* Bug #78888 for the Windows case */
832 if (state->operation == AIO_OP_CONNECT && state->blocking == TRUE) {
833 //FIXME: increment number of threads while this one is waiting?
834 threadpool_append_job (&async_io_tp, (MonoObject *) state);
838 WaitForSingleObject (data->new_sem, INFINITE);
839 if (data->newpfd == NULL)
840 data->newpfd = g_new0 (mono_pollfd, 1);
842 EnterCriticalSection (&data->io_lock);
843 if (data->sock_to_state == NULL) {
844 LeaveCriticalSection (&data->io_lock);
848 /* FIXME: 64 bit issue: handle can be a pointer on windows? */
849 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (state->handle));
851 list = mono_mlist_alloc ((MonoObject*)state);
853 list = mono_mlist_append (list, (MonoObject*)state);
856 events = get_events_from_list (list);
857 INIT_POLLFD (data->newpfd, GPOINTER_TO_INT (state->handle), events);
858 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (state->handle), list);
859 LeaveCriticalSection (&data->io_lock);
860 *msg = (char) state->operation;
862 w = write (data->pipe [1], msg, 1);
865 send ((SOCKET) data->pipe [1], msg, 1, 0);
871 socket_io_add_epoll (MonoSocketAsyncResult *state)
874 SocketIOData *data = &socket_io_data;
875 struct epoll_event event;
879 if (mono_runtime_is_shutting_down () || data->inited == 3 || data->sock_to_state == NULL)
882 memset (&event, 0, sizeof (struct epoll_event));
883 fd = GPOINTER_TO_INT (state->handle);
884 EnterCriticalSection (&data->io_lock);
885 if (data->sock_to_state == NULL) {
886 LeaveCriticalSection (&data->io_lock);
889 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
891 list = mono_mlist_alloc ((MonoObject*)state);
892 epoll_op = EPOLL_CTL_ADD;
894 list = mono_mlist_append (list, (MonoObject*)state);
895 epoll_op = EPOLL_CTL_MOD;
898 ievt = get_events_from_list (list);
899 if ((ievt & MONO_POLLIN) != 0)
900 event.events |= EPOLLIN;
901 if ((ievt & MONO_POLLOUT) != 0)
902 event.events |= EPOLLOUT;
904 mono_g_hash_table_replace (data->sock_to_state, state->handle, list);
906 EPOLL_DEBUG ("%s %d with %d", epoll_op == EPOLL_CTL_ADD ? "ADD" : "MOD", fd, event.events);
907 if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
909 if (epoll_op == EPOLL_CTL_ADD && err == EEXIST) {
910 epoll_op = EPOLL_CTL_MOD;
911 if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
912 g_message ("epoll_ctl(MOD): %d %s", err, g_strerror (err));
916 LeaveCriticalSection (&data->io_lock);
923 socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
925 if (async_tp.pool_status == 2 || mono_runtime_is_shutting_down ())
928 socket_io_init (&socket_io_data);
930 MONO_OBJECT_SETREF (state, ares, ares);
932 if (socket_io_data.epoll_disabled == FALSE) {
933 if (socket_io_add_epoll (state))
937 socket_io_add_poll (state);
940 #ifndef DISABLE_SOCKETS
942 socket_io_filter (MonoObject *target, MonoObject *state)
945 MonoSocketAsyncResult *sock_res = (MonoSocketAsyncResult *) state;
948 if (target == NULL || state == NULL)
951 if (socket_async_call_klass == NULL) {
952 klass = target->vtable->klass;
953 /* Check if it's SocketAsyncCall in System.Net.Sockets
954 * FIXME: check the assembly is signed correctly for extra care
956 if (klass->name [0] == 'S' && strcmp (klass->name, "SocketAsyncCall") == 0
957 && strcmp (mono_image_get_name (klass->image), "System") == 0
958 && klass->nested_in && strcmp (klass->nested_in->name, "Socket") == 0)
959 socket_async_call_klass = klass;
962 if (process_async_call_klass == NULL) {
963 klass = target->vtable->klass;
964 /* Check if it's AsyncReadHandler in System.Diagnostics.Process
965 * FIXME: check the assembly is signed correctly for extra care
967 if (klass->name [0] == 'A' && strcmp (klass->name, "AsyncReadHandler") == 0
968 && strcmp (mono_image_get_name (klass->image), "System") == 0
969 && klass->nested_in && strcmp (klass->nested_in->name, "Process") == 0)
970 process_async_call_klass = klass;
972 /* return both when socket_async_call_klass has not been seen yet and when
973 * the object is not an instance of the class.
975 if (target->vtable->klass != socket_async_call_klass && target->vtable->klass != process_async_call_klass)
978 op = sock_res->operation;
979 if (op < AIO_OP_FIRST || op >= AIO_OP_LAST)
984 #endif /* !DISABLE_SOCKETS */
986 /* Returns the exception thrown when invoking, if any */
988 mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares)
990 ASyncCall *ac = (ASyncCall *)ares->object_data;
991 MonoObject *res, *exc = NULL;
992 MonoArray *out_args = NULL;
993 HANDLE wait_event = NULL;
995 if (ares->execution_context) {
996 /* use captured ExecutionContext (if available) */
997 MONO_OBJECT_SETREF (ares, original_context, mono_thread_get_execution_context ());
998 mono_thread_set_execution_context (ares->execution_context);
1000 ares->original_context = NULL;
1004 /* Fast path from ThreadPool.*QueueUserWorkItem */
1005 void *pa = ares->async_state;
1006 mono_runtime_delegate_invoke (ares->async_delegate, &pa, &exc);
1008 MonoObject *cb_exc = NULL;
1010 ac->msg->exc = NULL;
1011 res = mono_message_invoke (ares->async_delegate, ac->msg, &exc, &out_args);
1012 MONO_OBJECT_SETREF (ac, res, res);
1013 MONO_OBJECT_SETREF (ac, msg->exc, exc);
1014 MONO_OBJECT_SETREF (ac, out_args, out_args);
1016 mono_monitor_enter ((MonoObject *) ares);
1017 ares->completed = 1;
1018 if (ares->handle != NULL)
1019 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
1020 mono_monitor_exit ((MonoObject *) ares);
1021 /* notify listeners */
1022 if (wait_event != NULL)
1023 SetEvent (wait_event);
1025 /* call async callback if cb_method != null*/
1026 if (ac != NULL && ac->cb_method) {
1029 mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &cb_exc);
1030 MONO_OBJECT_SETREF (ac->msg, exc, cb_exc);
1037 /* restore original thread execution context if flow isn't suppressed, i.e. non null */
1038 if (ares->original_context) {
1039 mono_thread_set_execution_context (ares->original_context);
1040 ares->original_context = NULL;
1046 threadpool_start_idle_threads (ThreadPool *tp)
1050 if (tp->pool_status == 1 && !tp->is_io)
1051 mono_thread_create_internal (mono_get_root_domain (), monitor_thread, tp, TRUE);
1055 if (n >= tp->min_threads)
1057 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n)
1060 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
1061 mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE);
1062 SleepEx (100, TRUE);
1067 threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer))
1069 memset (tp, 0, sizeof (ThreadPool));
1070 MONO_SEM_INIT (&tp->lock, 1);
1071 tp->min_threads = min_threads;
1072 tp->max_threads = max_threads;
1073 tp->async_invoke = async_invoke;
1074 MONO_SEM_INIT (&tp->new_job, 0);
1078 init_perf_counter (const char *category, const char *counter)
1080 MonoString *category_str;
1081 MonoString *counter_str;
1082 MonoString *machine;
1087 if (category == NULL || counter == NULL)
1089 root = mono_get_root_domain ();
1090 category_str = mono_string_new (root, category);
1091 counter_str = mono_string_new (root, counter);
1092 machine = mono_string_new (root, ".");
1093 return mono_perfcounter_get_impl (category_str, counter_str, NULL, machine, &type, &custom);
1098 print_pool_info (ThreadPool *tp)
1101 // if (tp->tail - tp->head == 0)
1104 g_print ("Pool status? %d\n", InterlockedCompareExchange (&tp->pool_status, 0, 0));
1105 g_print ("Min. threads: %d\n", InterlockedCompareExchange (&tp->min_threads, 0, 0));
1106 g_print ("Max. threads: %d\n", InterlockedCompareExchange (&tp->max_threads, 0, 0));
1107 g_print ("nthreads: %d\n", InterlockedCompareExchange (&tp->nthreads, 0, 0));
1108 g_print ("busy threads: %d\n", InterlockedCompareExchange (&tp->busy_threads, 0, 0));
1109 g_print ("Waiting: %d\n", InterlockedCompareExchange (&tp->waiting, 0, 0));
1110 g_print ("Queued: %d\n", (tp->tail - tp->head));
1111 if (tp == &async_tp) {
1113 EnterCriticalSection (&wsqs_lock);
1114 for (i = 0; i < wsqs->len; i++) {
1115 g_print ("\tWSQ %d: %d\n", i, mono_wsq_count (g_ptr_array_index (wsqs, i)));
1117 LeaveCriticalSection (&wsqs_lock);
1119 g_print ("\tSockets: %d\n", mono_g_hash_table_size (socket_io_data.sock_to_state));
1121 g_print ("-------------\n");
1125 signal_handler (int signo)
1130 MONO_SEM_WAIT (&tp->lock);
1131 g_print ("\n-----Non-IO-----\n");
1132 print_pool_info (tp);
1133 MONO_SEM_POST (&tp->lock);
1135 MONO_SEM_WAIT (&tp->lock);
1136 g_print ("\n-----IO-----\n");
1137 print_pool_info (tp);
1138 MONO_SEM_POST (&tp->lock);
1144 monitor_thread (gpointer data)
1147 MonoInternalThread *thread;
1153 thread = mono_thread_internal_current ();
1158 ts = mono_msec_ticks ();
1159 if (SleepEx (ms, TRUE) == 0)
1161 ms -= (mono_msec_ticks () - ts);
1162 if (mono_runtime_is_shutting_down ())
1164 if (THREAD_WANTS_A_BREAK (thread))
1165 mono_thread_interruption_checkpoint ();
1168 if (mono_runtime_is_shutting_down ())
1170 if (tp->waiting > 0)
1172 MONO_SEM_WAIT (&tp->lock);
1173 need_one = (tp->head != tp->tail);
1175 EnterCriticalSection (&wsqs_lock);
1176 for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
1178 wsq = g_ptr_array_index (wsqs, i);
1179 if (mono_wsq_count (wsq) > 0) {
1184 LeaveCriticalSection (&wsqs_lock);
1186 MONO_SEM_POST (&tp->lock);
1188 threadpool_start_thread (tp);
1193 mono_thread_pool_init ()
1195 gint threads_per_cpu = 1;
1197 gint cpu_count = mono_cpu_count ();
1203 result = InterlockedCompareExchange (&tp_inited, 1, 0);
1212 MONO_GC_REGISTER_ROOT_SINGLE (async_tp.first);
1213 MONO_GC_REGISTER_ROOT_SINGLE (async_tp.last);
1214 MONO_GC_REGISTER_ROOT_SINGLE (async_tp.unused);
1215 MONO_GC_REGISTER_ROOT_SINGLE (async_io_tp.first);
1216 MONO_GC_REGISTER_ROOT_SINGLE (async_io_tp.unused);
1217 MONO_GC_REGISTER_ROOT_SINGLE (async_io_tp.last);
1219 MONO_GC_REGISTER_ROOT_FIXED (socket_io_data.sock_to_state);
1220 InitializeCriticalSection (&socket_io_data.io_lock);
1221 if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
1222 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
1223 if (threads_per_cpu < 1)
1224 threads_per_cpu = 1;
1227 thread_count = MIN (cpu_count * threads_per_cpu, 100 * cpu_count);
1228 threadpool_init (&async_tp, thread_count, MAX (100 * cpu_count, thread_count), async_invoke_thread);
1229 threadpool_init (&async_io_tp, cpu_count * 2, cpu_count * 4, async_invoke_thread);
1230 async_io_tp.is_io = TRUE;
1232 async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
1233 g_assert (async_call_klass);
1235 InitializeCriticalSection (&wsqs_lock);
1236 wsqs = g_ptr_array_sized_new (MAX (100 * cpu_count, thread_count));
1239 async_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "Work Items Added");
1240 g_assert (async_tp.pc_nitems);
1242 async_io_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "IO Work Items Added");
1243 g_assert (async_io_tp.pc_nitems);
1245 async_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of Threads");
1246 g_assert (async_tp.pc_nthreads);
1248 async_io_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of IO Threads");
1249 g_assert (async_io_tp.pc_nthreads);
1252 signal (SIGALRM, signal_handler);
1258 icall_append_io_job (MonoObject *target, MonoSocketAsyncResult *state)
1260 MonoDomain *domain = mono_domain_get ();
1261 MonoAsyncResult *ares;
1263 /* Don't call mono_async_result_new() to avoid capturing the context */
1264 ares = (MonoAsyncResult *) mono_object_new (domain, mono_defaults.asyncresult_class);
1265 MONO_OBJECT_SETREF (ares, async_delegate, target);
1266 MONO_OBJECT_SETREF (ares, async_state, state);
1267 socket_io_add (ares, state);
1271 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
1274 MonoDomain *domain = mono_domain_get ();
1275 MonoAsyncResult *ares;
1278 ac = (ASyncCall*)mono_object_new (domain, async_call_klass);
1279 MONO_OBJECT_SETREF (ac, msg, msg);
1280 MONO_OBJECT_SETREF (ac, state, state);
1282 if (async_callback) {
1283 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
1284 MONO_OBJECT_SETREF (ac, cb_target, async_callback);
1287 ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
1288 MONO_OBJECT_SETREF (ares, async_delegate, target);
1290 #ifndef DISABLE_SOCKETS
1291 if (socket_io_filter (target, state)) {
1292 socket_io_add (ares, (MonoSocketAsyncResult *) state);
1296 threadpool_append_job (&async_tp, (MonoObject *) ares);
1301 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1309 /* check if already finished */
1310 mono_monitor_enter ((MonoObject *) ares);
1312 if (ares->endinvoke_called) {
1313 *exc = (MonoObject *) mono_get_exception_invalid_operation (NULL);
1314 mono_monitor_exit ((MonoObject *) ares);
1318 ares->endinvoke_called = 1;
1319 /* wait until we are really finished */
1320 if (!ares->completed) {
1321 if (ares->handle == NULL) {
1322 wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1323 g_assert(wait_event != 0);
1324 MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), wait_event));
1326 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
1328 mono_monitor_exit ((MonoObject *) ares);
1329 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
1331 mono_monitor_exit ((MonoObject *) ares);
1334 ac = (ASyncCall *) ares->object_data;
1335 g_assert (ac != NULL);
1336 *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1337 *out_args = ac->out_args;
1343 threadpool_kill_idle_threads (ThreadPool *tp)
1347 n = (gint) InterlockedCompareExchange (&tp->max_threads, 0, -1);
1350 MONO_SEM_POST (&tp->new_job);
1355 mono_thread_pool_cleanup (void)
1357 if (!(async_tp.pool_status == 0 || async_tp.pool_status == 2)) {
1358 if (!(async_tp.pool_status == 1 && InterlockedCompareExchange (&async_tp.pool_status, 2, 1) == 2)) {
1359 InterlockedExchange (&async_io_tp.pool_status, 2);
1360 MONO_SEM_WAIT (&async_tp.lock);
1361 threadpool_free_queue (&async_tp);
1362 threadpool_kill_idle_threads (&async_tp);
1363 MONO_SEM_POST (&async_tp.lock);
1365 socket_io_cleanup (&socket_io_data); /* Empty when DISABLE_SOCKETS is defined */
1366 MONO_SEM_WAIT (&async_io_tp.lock);
1367 threadpool_free_queue (&async_io_tp);
1368 threadpool_kill_idle_threads (&async_io_tp);
1369 MONO_SEM_POST (&async_io_tp.lock);
1370 MONO_SEM_DESTROY (&async_io_tp.new_job);
1374 EnterCriticalSection (&wsqs_lock);
1375 mono_wsq_cleanup ();
1377 g_ptr_array_free (wsqs, TRUE);
1379 LeaveCriticalSection (&wsqs_lock);
1380 MONO_SEM_DESTROY (&async_tp.new_job);
1383 /* Caller must enter &tp->lock */
1385 dequeue_job_nolock (ThreadPool *tp)
1393 if (mono_runtime_is_shutting_down ())
1395 if (!list || tp->head == tp->tail)
1398 array = (MonoArray *) mono_mlist_get_data (list);
1399 ar = mono_array_get (array, MonoObject *, tp->head % QUEUE_LENGTH);
1400 mono_array_set (array, MonoObject *, tp->head % QUEUE_LENGTH, NULL);
1402 if ((tp->head % QUEUE_LENGTH) == 0) {
1404 tp->first = mono_mlist_next (list);
1405 if (tp->first == NULL)
1407 if (mono_mlist_length (tp->unused) < 20) {
1408 /* reuse this chunk */
1409 tp->unused = mono_mlist_set_next (list, tp->unused);
1411 tp->head -= QUEUE_LENGTH;
1412 tp->tail -= QUEUE_LENGTH;
1415 } while (ar == NULL);
1420 threadpool_start_thread (ThreadPool *tp)
1424 while (!mono_runtime_is_shutting_down () && (n = tp->nthreads) < tp->max_threads) {
1425 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n) {
1426 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
1427 mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE);
1436 pulse_on_new_job (ThreadPool *tp)
1439 MONO_SEM_POST (&tp->new_job);
1443 icall_append_job (MonoObject *ar)
1445 threadpool_append_job (&async_tp, ar);
1449 threadpool_append_job (ThreadPool *tp, MonoObject *ar)
1451 threadpool_append_jobs (tp, &ar, 1);
1455 create_or_reuse_list (ThreadPool *tp)
1463 tp->unused = mono_mlist_next (list);
1464 mono_mlist_set_next (list, NULL);
1465 //TP_DEBUG (tp->nodes_reused++);
1467 array = mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, QUEUE_LENGTH);
1468 list = mono_mlist_alloc ((MonoObject *) array);
1469 //TP_DEBUG (tp->nodes_created++);
1475 threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs)
1477 static int job_counter;
1482 gboolean lock_taken = FALSE; /* We won't take the lock when the local queue is used */
1484 if (mono_runtime_is_shutting_down ())
1487 if (tp->pool_status == 0 && InterlockedCompareExchange (&tp->pool_status, 1, 0) == 0)
1488 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, tp, TRUE);
1490 for (i = 0; i < njobs; i++) {
1492 if (ar == NULL || mono_domain_is_unloading (ar->vtable->domain))
1493 continue; /* Might happen when cleaning domain jobs */
1494 if (!tp->is_io && (InterlockedIncrement (&job_counter) % 10) == 0) {
1495 MonoAsyncResult *o = (MonoAsyncResult *) ar;
1496 o->add_time = mono_100ns_ticks ();
1498 threadpool_jobs_inc (ar);
1499 mono_perfcounter_update_value (tp->pc_nitems, TRUE, 1);
1500 if (!tp->is_io && mono_wsq_local_push (ar))
1504 MONO_SEM_WAIT (&tp->lock);
1507 if ((tp->tail % QUEUE_LENGTH) == 0) {
1508 list = create_or_reuse_list (tp);
1509 if (tp->last != NULL)
1510 mono_mlist_set_next (tp->last, list);
1512 if (tp->first == NULL)
1513 tp->first = tp->last;
1516 array = (MonoArray *) mono_mlist_get_data (tp->last);
1517 mono_array_setref (array, tp->tail % QUEUE_LENGTH, ar);
1521 MONO_SEM_POST (&tp->lock);
1523 for (i = 0; i < MIN(njobs, tp->max_threads); i++)
1524 pulse_on_new_job (tp);
1528 threadpool_clear_queue (ThreadPool *tp, MonoDomain *domain)
1537 MONO_SEM_WAIT (&tp->lock);
1538 current = tp->first;
1540 array = (MonoArray *) mono_mlist_get_data (current);
1541 for (i = 0; i < QUEUE_LENGTH; i++) {
1542 obj = mono_array_get (array, MonoObject*, i);
1543 if (obj != NULL && obj->vtable->domain == domain) {
1545 mono_array_setref (array, i, NULL);
1546 threadpool_jobs_dec (obj);
1549 current = mono_mlist_next (current);
1552 if (!domain_count) {
1553 MONO_SEM_POST (&tp->lock);
1557 current = tp->first;
1562 MONO_SEM_POST (&tp->lock);
1563 /* Re-add everything but the nullified elements */
1565 array = (MonoArray *) mono_mlist_get_data (current);
1566 threadpool_append_jobs (tp, mono_array_addr (array, MonoObject *, 0), QUEUE_LENGTH);
1567 memset (mono_array_addr (array, MonoObject *, 0), 0, sizeof (MonoObject *) * QUEUE_LENGTH);
1568 current = mono_mlist_next (current);
1573 * Clean up the threadpool of all domain jobs.
1574 * Can only be called as part of the domain unloading process as
1575 * it will wait for all jobs to be visible to the interruption code.
1578 mono_thread_pool_remove_domain_jobs (MonoDomain *domain, int timeout)
1582 guint32 start_time = 0;
1584 g_assert (domain->state == MONO_APPDOMAIN_UNLOADING);
1586 threadpool_clear_queue (&async_tp, domain);
1587 threadpool_clear_queue (&async_io_tp, domain);
1590 * There might be some threads out that could be about to execute stuff from the given domain.
1591 * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
1593 sem_handle = CreateSemaphore (NULL, 0, 1, NULL);
1595 domain->cleanup_semaphore = sem_handle;
1597 * The memory barrier here is required to have global ordering between assigning to cleanup_semaphone
1598 * and reading threadpool_jobs.
1599 * Otherwise this thread could read a stale version of threadpool_jobs and wait forever.
1601 mono_memory_write_barrier ();
1603 if (domain->threadpool_jobs && timeout != -1)
1604 start_time = mono_msec_ticks ();
1605 while (domain->threadpool_jobs) {
1606 WaitForSingleObject (sem_handle, timeout);
1607 if (timeout != -1 && (mono_msec_ticks () - start_time) > timeout) {
1613 domain->cleanup_semaphore = NULL;
1614 CloseHandle (sem_handle);
1619 threadpool_free_queue (ThreadPool *tp)
1621 tp->head = tp->tail = 0;
1627 mono_thread_pool_is_queue_array (MonoArray *o)
1631 // FIXME: need some fix in sgen code.
1632 // There are roots at: async*tp.unused (MonoMList) and wsqs [n]->queue (MonoArray)
1633 return obj == async_tp.first || obj == async_io_tp.first;
1642 EnterCriticalSection (&wsqs_lock);
1643 wsq = mono_wsq_create ();
1645 LeaveCriticalSection (&wsqs_lock);
1648 for (i = 0; i < wsqs->len; i++) {
1649 if (g_ptr_array_index (wsqs, i) == NULL) {
1650 wsqs->pdata [i] = wsq;
1651 LeaveCriticalSection (&wsqs_lock);
1655 g_ptr_array_add (wsqs, wsq);
1656 LeaveCriticalSection (&wsqs_lock);
1661 remove_wsq (MonoWSQ *wsq)
1668 EnterCriticalSection (&wsqs_lock);
1670 LeaveCriticalSection (&wsqs_lock);
1673 g_ptr_array_remove_fast (wsqs, wsq);
1675 while (mono_wsq_local_pop (&data)) {
1676 threadpool_jobs_dec (data);
1679 mono_wsq_destroy (wsq);
1680 LeaveCriticalSection (&wsqs_lock);
1684 try_steal (gpointer *data, gboolean retry)
1689 if (wsqs == NULL || data == NULL || *data != NULL)
1694 if (mono_runtime_is_shutting_down ())
1696 for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
1697 if (mono_runtime_is_shutting_down ()) {
1700 mono_wsq_try_steal (wsqs->pdata [i], data, ms);
1701 if (*data != NULL) {
1706 } while (retry && ms < 11);
1710 dequeue_or_steal (ThreadPool *tp, gpointer *data)
1712 if (mono_runtime_is_shutting_down ())
1714 TP_DEBUG ("Dequeue");
1715 MONO_SEM_WAIT (&tp->lock);
1716 *data = dequeue_job_nolock (tp);
1717 MONO_SEM_POST (&tp->lock);
1718 if (!tp->is_io && !*data)
1719 try_steal (data, FALSE);
1720 return (*data != NULL);
1724 process_idle_times (ThreadPool *tp, gint64 t)
1728 gboolean compute_avg;
1732 if (tp->ignore_times || t <= 0)
1735 compute_avg = FALSE;
1736 ticks = mono_100ns_ticks ();
1738 SPIN_LOCK (tp->sp_lock);
1739 if (tp->ignore_times) {
1740 SPIN_UNLOCK (tp->sp_lock);
1745 if (tp->last_check == 0)
1746 tp->last_check = ticks;
1747 else if (tp->last_check > 0 && (ticks - tp->last_check) > 5000000) {
1748 tp->ignore_times = 1;
1751 SPIN_UNLOCK (tp->sp_lock);
1756 //printf ("Items: %d Time elapsed: %.3fs\n", tp->n_sum, (ticks - tp->last_check) / 10000.0);
1757 tp->last_check = ticks;
1759 avg = tp->time_sum / tp->n_sum;
1760 if (tp->averages [1] == 0) {
1761 tp->averages [1] = avg;
1763 per1 = ((100 * (ABS (avg - tp->averages [1]))) / tp->averages [1]);
1765 if (avg > tp->averages [1]) {
1766 if (tp->averages [1] < tp->averages [0]) {
1771 } else if (avg < tp->averages [1] && tp->averages [1] < tp->averages [0]) {
1776 min = tp->min_threads;
1778 if ((n - min) < min && tp->busy_threads == n)
1782 if (new_threads != 0) {
1783 printf ("n: %d per1: %lld avg=%lld avg1=%lld avg0=%lld\n", new_threads, per1, avg, tp->averages [1], tp->averages [0]);
1791 tp->averages [0] = tp->averages [1];
1792 tp->averages [1] = avg;
1793 tp->ignore_times = 0;
1795 if (new_threads == -1) {
1796 if (tp->destroy_thread == 0 && InterlockedCompareExchange (&tp->destroy_thread, 1, 0) == 0)
1797 pulse_on_new_job (tp);
1802 should_i_die (ThreadPool *tp)
1804 gboolean result = FALSE;
1805 if (tp->destroy_thread == 1 && InterlockedCompareExchange (&tp->destroy_thread, 0, 1) == 1)
1806 result = (tp->nthreads > tp->min_threads);
1811 async_invoke_thread (gpointer data)
1814 MonoInternalThread *thread;
1824 thread = mono_thread_internal_current ();
1826 tp_start_func (tp_hooks_user_data);
1829 MonoAsyncResult *ar;
1830 gboolean is_io_task;
1834 ar = (MonoAsyncResult *) data;
1836 InterlockedIncrement (&tp->busy_threads);
1837 #ifndef DISABLE_SOCKETS
1838 is_io_task = (strcmp (((MonoObject *) data)->vtable->klass->name, "AsyncResult"));
1840 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1842 switch (state->operation) {
1843 case AIO_OP_RECEIVE:
1844 state->total = ICALL_RECV (state);
1847 state->total = ICALL_SEND (state);
1852 /* worker threads invokes methods in different domains,
1853 * so we need to set the right domain here */
1854 domain = ((MonoObject *)ar)->vtable->domain;
1857 if (mono_domain_is_unloading (domain) || mono_runtime_is_shutting_down ()) {
1858 threadpool_jobs_dec ((MonoObject *)ar);
1861 InterlockedDecrement (&tp->busy_threads);
1863 mono_thread_push_appdomain_ref (domain);
1864 if (threadpool_jobs_dec ((MonoObject *)ar)) {
1867 mono_thread_pop_appdomain_ref ();
1868 InterlockedDecrement (&tp->busy_threads);
1872 if (mono_domain_set (domain, FALSE)) {
1875 if (tp_item_begin_func)
1876 tp_item_begin_func (tp_item_user_data);
1878 if (!is_io_task && ar->add_time > 0)
1879 process_idle_times (tp, ar->add_time);
1880 exc = mono_async_invoke (tp, ar);
1881 if (tp_item_end_func)
1882 tp_item_end_func (tp_item_user_data);
1883 if (exc && mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_CURRENT) {
1887 klass = exc->vtable->klass;
1888 unloaded = (klass->image == mono_defaults.corlib);
1890 unloaded = (!strcmp ("System", klass->name_space) &&
1891 !strcmp ("AppDomainUnloadedException", klass->name));
1894 if (!unloaded && klass != mono_defaults.threadabortexception_class) {
1895 mono_unhandled_exception (exc);
1899 mono_domain_set (mono_get_root_domain (), TRUE);
1901 mono_thread_pop_appdomain_ref ();
1902 InterlockedDecrement (&tp->busy_threads);
1903 /* If the callee changes the background status, set it back to TRUE */
1904 if (!mono_thread_test_state (thread , ThreadState_Background))
1905 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
1911 must_die = should_i_die (tp);
1912 TP_DEBUG ("Trying to get a job");
1913 if (!must_die && (tp->is_io || !mono_wsq_local_pop (&data)))
1914 dequeue_or_steal (tp, &data);
1915 TP_DEBUG ("Done trying to get a job %p", data);
1918 while (!must_die && !data && n_naps < 4) {
1921 TP_DEBUG ("Waiting");
1922 InterlockedIncrement (&tp->waiting);
1923 #if defined(__OpenBSD__)
1924 while ((res = mono_sem_wait (&tp->new_job, TRUE)) == -1) {// && errno == EINTR) {
1926 while ((res = mono_sem_timedwait (&tp->new_job, 2000, TRUE)) == -1) {// && errno == EINTR) {
1928 if (mono_runtime_is_shutting_down ())
1930 if (THREAD_WANTS_A_BREAK (thread))
1931 mono_thread_interruption_checkpoint ();
1933 TP_DEBUG ("Done waiting");
1934 InterlockedDecrement (&tp->waiting);
1935 if (mono_runtime_is_shutting_down ())
1937 must_die = should_i_die (tp);
1938 dequeue_or_steal (tp, &data);
1942 if (!data && tp->is_io && !mono_runtime_is_shutting_down ()) {
1943 mono_wsq_local_pop (&data);
1944 if (data && must_die) {
1945 InterlockedCompareExchange (&tp->destroy_thread, 1, 0);
1946 pulse_on_new_job (tp);
1955 down = mono_runtime_is_shutting_down ();
1956 if (!down && nt <= tp->min_threads)
1958 if (down || InterlockedCompareExchange (&tp->nthreads, nt - 1, nt) == nt) {
1959 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, -1);
1965 tp_finish_func (tp_hooks_user_data);
1972 g_assert_not_reached ();
1976 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
1978 *workerThreads = async_tp.max_threads - async_tp.busy_threads;
1979 *completionPortThreads = async_io_tp.max_threads - async_io_tp.busy_threads;
1983 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
1985 *workerThreads = async_tp.max_threads;
1986 *completionPortThreads = async_io_tp.max_threads;
1990 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
1992 *workerThreads = async_tp.min_threads;
1993 *completionPortThreads = async_io_tp.min_threads;
1997 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
2000 gint max_io_threads;
2002 max_threads = async_tp.max_threads;
2003 if (workerThreads <= 0 || workerThreads > max_threads)
2006 max_io_threads = async_io_tp.max_threads;
2007 if (completionPortThreads <= 0 || completionPortThreads > max_io_threads)
2010 InterlockedExchange (&async_tp.min_threads, workerThreads);
2011 InterlockedExchange (&async_io_tp.min_threads, completionPortThreads);
2012 if (workerThreads > async_tp.nthreads)
2013 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_tp, TRUE);
2014 if (completionPortThreads > async_io_tp.nthreads)
2015 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_io_tp, TRUE);
2020 ves_icall_System_Threading_ThreadPool_SetMaxThreads (gint workerThreads, gint completionPortThreads)
2023 gint min_io_threads;
2026 cpu_count = mono_cpu_count ();
2027 min_threads = async_tp.min_threads;
2028 if (workerThreads < min_threads || workerThreads < cpu_count)
2031 /* We don't really have the concept of completion ports. Do we care here? */
2032 min_io_threads = async_io_tp.min_threads;
2033 if (completionPortThreads < min_io_threads || completionPortThreads < cpu_count)
2036 InterlockedExchange (&async_tp.max_threads, workerThreads);
2037 InterlockedExchange (&async_io_tp.max_threads, completionPortThreads);
2042 * mono_install_threadpool_thread_hooks
2043 * @start_func: the function to be called right after a new threadpool thread is created. Can be NULL.
2044 * @finish_func: the function to be called right before a thredpool thread is exiting. Can be NULL.
2045 * @user_data: argument passed to @start_func and @finish_func.
2047 * @start_fun will be called right after a threadpool thread is created and @finish_func right before a threadpool thread exits.
2048 * The calls will be made from the thread itself.
2051 mono_install_threadpool_thread_hooks (MonoThreadPoolFunc start_func, MonoThreadPoolFunc finish_func, gpointer user_data)
2053 tp_start_func = start_func;
2054 tp_finish_func = finish_func;
2055 tp_hooks_user_data = user_data;
2059 * mono_install_threadpool_item_hooks
2060 * @begin_func: the function to be called before a threadpool work item processing starts.
2061 * @end_func: the function to be called after a threadpool work item is finished.
2062 * @user_data: argument passed to @begin_func and @end_func.
2064 * The calls will be made from the thread itself and from the same AppDomain
2065 * where the work item was executed.
2069 mono_install_threadpool_item_hooks (MonoThreadPoolItemFunc begin_func, MonoThreadPoolItemFunc end_func, gpointer user_data)
2071 tp_item_begin_func = begin_func;
2072 tp_item_end_func = end_func;
2073 tp_item_user_data = user_data;