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,
210 #ifdef DISABLE_SOCKETS
212 #define socket_io_cleanup(x)
215 get_event_from_state (MonoSocketAsyncResult *state)
217 g_assert_not_reached ();
222 get_events_from_list (MonoMList *list)
230 socket_io_cleanup (SocketIOData *data)
232 EnterCriticalSection (&data->io_lock);
233 if (data->inited != 2) {
234 LeaveCriticalSection (&data->io_lock);
240 closesocket (data->pipe [0]);
241 closesocket (data->pipe [1]);
243 if (data->pipe [0] > -1)
244 close (data->pipe [0]);
245 if (data->pipe [1] > -1)
246 close (data->pipe [1]);
251 CloseHandle (data->new_sem);
252 data->new_sem = NULL;
253 mono_g_hash_table_destroy (data->sock_to_state);
254 data->sock_to_state = NULL;
255 g_free (data->newpfd);
258 if (FALSE == data->epoll_disabled)
259 close (data->epollfd);
261 LeaveCriticalSection (&data->io_lock);
265 get_event_from_state (MonoSocketAsyncResult *state)
267 switch (state->operation) {
270 case AIO_OP_RECV_JUST_CALLBACK:
271 case AIO_OP_RECEIVEFROM:
272 case AIO_OP_READPIPE:
275 case AIO_OP_SEND_JUST_CALLBACK:
279 default: /* Should never happen */
280 g_message ("get_event_from_state: unknown value in switch!!!");
286 get_events_from_list (MonoMList *list)
288 MonoSocketAsyncResult *state;
291 while (list && (state = (MonoSocketAsyncResult *)mono_mlist_get_data (list))) {
292 events |= get_event_from_state (state);
293 list = mono_mlist_next (list);
299 #define ICALL_RECV(x) ves_icall_System_Net_Sockets_Socket_Receive_internal (\
300 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
301 x->socket_flags, &x->error);
303 #define ICALL_SEND(x) ves_icall_System_Net_Sockets_Socket_Send_internal (\
304 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
305 x->socket_flags, &x->error);
307 #endif /* !DISABLE_SOCKETS */
310 threadpool_jobs_inc (MonoObject *obj)
313 InterlockedIncrement (&obj->vtable->domain->threadpool_jobs);
317 threadpool_jobs_dec (MonoObject *obj)
319 MonoDomain *domain = obj->vtable->domain;
320 int remaining_jobs = InterlockedDecrement (&domain->threadpool_jobs);
321 if (remaining_jobs == 0 && domain->cleanup_semaphore) {
322 ReleaseSemaphore (domain->cleanup_semaphore, 1, NULL);
330 get_io_event (MonoMList **list, gint event)
340 state = mono_mlist_get_data (current);
341 if (get_event_from_state ((MonoSocketAsyncResult *) state) == event)
346 current = mono_mlist_next (current);
351 mono_mlist_set_next (prev, mono_mlist_next (current));
353 *list = mono_mlist_next (*list);
362 process_io_event (MonoMList *list, int event)
364 MonoSocketAsyncResult *state;
370 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
371 if (get_event_from_state (state) == event)
374 list = mono_mlist_next (list);
378 oldlist = mono_mlist_remove_item (oldlist, list);
379 EPOLL_DEBUG ("Dispatching event %d on socket %p", event, state->handle);
380 threadpool_append_job (&async_io_tp, (MonoObject *) state);
387 mark_bad_fds (mono_pollfd *pfds, int nfds)
393 for (i = 0; i < nfds; i++) {
398 ret = mono_poll (pfd, 1, 0);
399 if (ret == -1 && errno == EBADF) {
400 pfd->revents |= MONO_POLLNVAL;
402 } else if (ret == 1) {
411 socket_io_poll_main (gpointer p)
413 #if MONO_SMALL_CONFIG
414 #define INITIAL_POLLFD_SIZE 128
416 #define INITIAL_POLLFD_SIZE 1024
418 #define POLL_ERRORS (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL)
419 SocketIOData *data = p;
424 MonoInternalThread *thread;
426 thread = mono_thread_internal_current ();
428 allocated = INITIAL_POLLFD_SIZE;
429 pfds = g_new0 (mono_pollfd, allocated);
430 INIT_POLLFD (pfds, data->pipe [0], MONO_POLLIN);
431 for (i = 1; i < allocated; i++)
432 INIT_POLLFD (&pfds [i], -1, 0);
442 if (THREAD_WANTS_A_BREAK (thread))
443 mono_thread_interruption_checkpoint ();
446 nsock = mono_poll (pfds, maxfd, -1);
447 } while (nsock == -1 && errno == EINTR);
450 * Apart from EINTR, we only check EBADF, for the rest:
451 * EINVAL: mono_poll() 'protects' us from descriptor
452 * numbers above the limit if using select() by marking
453 * then as MONO_POLLERR. If a system poll() is being
454 * used, the number of descriptor we're passing will not
455 * be over sysconf(_SC_OPEN_MAX), as the error would have
456 * happened when opening.
458 * EFAULT: we own the memory pointed by pfds.
459 * ENOMEM: we're doomed anyway
463 if (nsock == -1 && errno == EBADF) {
464 pfds->revents = 0; /* Just in case... */
465 nsock = mark_bad_fds (pfds, maxfd);
468 if ((pfds->revents & POLL_ERRORS) != 0) {
469 /* We're supposed to die now, as the pipe has been closed */
471 socket_io_cleanup (data);
475 /* Got a new socket */
476 if ((pfds->revents & MONO_POLLIN) != 0) {
479 for (i = 1; i < allocated; i++) {
481 if (pfd->fd == -1 || data->newpfd == NULL ||
482 pfd->fd == data->newpfd->fd)
486 if (i == allocated) {
491 allocated = allocated * 2;
492 pfds = g_renew (mono_pollfd, oldfd, allocated);
494 for (; i < allocated; i++)
495 INIT_POLLFD (&pfds [i], -1, 0);
498 nread = read (data->pipe [0], one, 1);
500 nread = recv ((SOCKET) data->pipe [0], one, 1, 0);
504 return; /* we're closed */
507 INIT_POLLFD (&pfds [i], data->newpfd->fd, data->newpfd->events);
508 ReleaseSemaphore (data->new_sem, 1, NULL);
517 EnterCriticalSection (&data->io_lock);
518 if (data->inited == 3) {
520 LeaveCriticalSection (&data->io_lock);
521 return; /* cleanup called */
524 for (i = 1; i < maxfd && nsock > 0; i++) {
526 if (pfd->fd == -1 || pfd->revents == 0)
530 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
531 if (list != NULL && (pfd->revents & (MONO_POLLIN | POLL_ERRORS)) != 0) {
532 list = process_io_event (list, MONO_POLLIN);
535 if (list != NULL && (pfd->revents & (MONO_POLLOUT | POLL_ERRORS)) != 0) {
536 list = process_io_event (list, MONO_POLLOUT);
540 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (pfd->fd), list);
541 pfd->events = get_events_from_list (list);
543 mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
549 LeaveCriticalSection (&data->io_lock);
554 #define EPOLL_ERRORS (EPOLLERR | EPOLLHUP)
555 #define EPOLL_NEVENTS 128
557 socket_io_epoll_main (gpointer p)
561 MonoInternalThread *thread;
562 struct epoll_event *events, *evt;
564 gpointer async_results [EPOLL_NEVENTS * 2]; // * 2 because each loop can add up to 2 results here
568 epollfd = data->epollfd;
569 thread = mono_thread_internal_current ();
570 events = g_new0 (struct epoll_event, EPOLL_NEVENTS);
575 if (THREAD_WANTS_A_BREAK (thread))
576 mono_thread_interruption_checkpoint ();
578 EPOLL_DEBUG ("epoll_wait init");
579 ready = epoll_wait (epollfd, events, EPOLL_NEVENTS, -1);
582 EPOLL_DEBUG ("epoll_wait end with %d ready sockets (%d %s).", ready, err, (ready == -1) ? g_strerror (err) : "");
585 } while (ready == -1 && errno == EINTR);
591 g_warning ("epoll_wait: %d %s", err, g_strerror (err));
597 EnterCriticalSection (&data->io_lock);
598 if (data->inited == 3) {
601 LeaveCriticalSection (&data->io_lock);
602 return; /* cleanup called */
606 for (i = 0; i < ready; i++) {
613 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
614 EPOLL_DEBUG ("Event %d on %d list length: %d", evt->events, fd, mono_mlist_length (list));
615 if (list != NULL && (evt->events & (EPOLLIN | EPOLL_ERRORS)) != 0) {
616 ares = get_io_event (&list, MONO_POLLIN);
618 async_results [nresults++] = ares;
621 if (list != NULL && (evt->events & (EPOLLOUT | EPOLL_ERRORS)) != 0) {
622 ares = get_io_event (&list, MONO_POLLOUT);
624 async_results [nresults++] = ares;
628 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (fd), list);
629 evt->events = get_events_from_list (list);
630 EPOLL_DEBUG ("MOD %d to %d", fd, evt->events);
631 if (epoll_ctl (epollfd, EPOLL_CTL_MOD, fd, evt)) {
632 if (epoll_ctl (epollfd, EPOLL_CTL_ADD, fd, evt) == -1) {
635 EPOLL_DEBUG ("epoll_ctl(MOD): %d %s fd: %d events: %d", err, g_strerror (err), fd, evt->events);
641 mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (fd));
642 EPOLL_DEBUG ("DEL %d", fd);
643 epoll_ctl (epollfd, EPOLL_CTL_DEL, fd, evt);
646 LeaveCriticalSection (&data->io_lock);
647 threadpool_append_jobs (&async_io_tp, (MonoObject **) async_results, nresults);
648 memset (async_results, 0, sizeof (gpointer) * nresults);
655 * select/poll wake up when a socket is closed, but epoll just removes
656 * the socket from its internal list without notification.
659 mono_thread_pool_remove_socket (int sock)
661 MonoMList *list, *next;
662 MonoSocketAsyncResult *state;
664 if (socket_io_data.inited == 0)
667 EnterCriticalSection (&socket_io_data.io_lock);
668 if (socket_io_data.sock_to_state == NULL) {
669 LeaveCriticalSection (&socket_io_data.io_lock);
672 list = mono_g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
674 mono_g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
675 LeaveCriticalSection (&socket_io_data.io_lock);
678 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
679 if (state->operation == AIO_OP_RECEIVE)
680 state->operation = AIO_OP_RECV_JUST_CALLBACK;
681 else if (state->operation == AIO_OP_SEND)
682 state->operation = AIO_OP_SEND_JUST_CALLBACK;
684 next = mono_mlist_remove_item (list, list);
685 list = process_io_event (list, MONO_POLLIN);
687 process_io_event (list, MONO_POLLOUT);
695 connect_hack (gpointer x)
697 struct sockaddr_in *addr = (struct sockaddr_in *) x;
700 while (connect ((SOCKET) socket_io_data.pipe [1], (SOCKADDR *) addr, sizeof (struct sockaddr_in))) {
703 g_warning ("Error initializing async. sockets %d.", WSAGetLastError ());
704 g_assert (WSAGetLastError ());
711 socket_io_init (SocketIOData *data)
714 struct sockaddr_in server;
715 struct sockaddr_in client;
722 if (data->inited >= 2) // 2 -> initialized, 3-> cleaned up
725 inited = InterlockedCompareExchange (&data->inited, 1, 0);
728 if (data->inited >= 2)
734 EnterCriticalSection (&data->io_lock);
737 data->epoll_disabled = (g_getenv ("MONO_DISABLE_AIO") != NULL);
738 if (FALSE == data->epoll_disabled) {
739 data->epollfd = epoll_create (256);
740 data->epoll_disabled = (data->epollfd == -1);
741 if (data->epoll_disabled && g_getenv ("MONO_DEBUG"))
742 g_message ("epoll_create() failed. Using plain poll().");
747 data->epoll_disabled = TRUE;
751 if (data->epoll_disabled) {
752 if (pipe (data->pipe) != 0) {
762 srv = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
763 g_assert (srv != INVALID_SOCKET);
764 data->pipe [1] = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
765 g_assert (data->pipe [1] != INVALID_SOCKET);
767 server.sin_family = AF_INET;
768 server.sin_addr.s_addr = inet_addr ("127.0.0.1");
770 if (bind (srv, (SOCKADDR *) &server, sizeof (server))) {
771 g_print ("%d\n", WSAGetLastError ());
775 len = sizeof (server);
776 getsockname (srv, (SOCKADDR *) &server, &len);
778 mono_thread_create (mono_get_root_domain (), connect_hack, &server);
779 len = sizeof (server);
780 data->pipe [0] = accept (srv, (SOCKADDR *) &client, &len);
781 g_assert (data->pipe [0] != INVALID_SOCKET);
784 data->sock_to_state = mono_g_hash_table_new_type (g_direct_hash, g_direct_equal, MONO_HASH_VALUE_GC);
786 if (data->epoll_disabled) {
787 data->new_sem = CreateSemaphore (NULL, 1, 1, NULL);
788 g_assert (data->new_sem != NULL);
791 stack_size = mono_threads_get_default_stacksize ();
792 mono_threads_set_default_stacksize (128 * 1024);
793 if (data->epoll_disabled) {
794 mono_thread_create_internal (mono_get_root_domain (), socket_io_poll_main, data, TRUE);
798 mono_thread_create_internal (mono_get_root_domain (), socket_io_epoll_main, data, TRUE);
801 mono_threads_set_default_stacksize (stack_size);
802 LeaveCriticalSection (&data->io_lock);
807 socket_io_add_poll (MonoSocketAsyncResult *state)
812 SocketIOData *data = &socket_io_data;
815 if (mono_runtime_is_shutting_down () || data->inited == 3 || data->sock_to_state == NULL)
818 #if defined(PLATFORM_MACOSX) || defined(PLATFORM_BSD) || defined(HOST_WIN32) || defined(PLATFORM_SOLARIS)
819 /* select() for connect() does not work well on the Mac. Bug #75436. */
820 /* Bug #77637 for the BSD 6 case */
821 /* Bug #78888 for the Windows case */
822 if (state->operation == AIO_OP_CONNECT && state->blocking == TRUE) {
823 //FIXME: increment number of threads while this one is waiting?
824 threadpool_append_job (&async_io_tp, (MonoObject *) state);
828 WaitForSingleObject (data->new_sem, INFINITE);
829 if (data->newpfd == NULL)
830 data->newpfd = g_new0 (mono_pollfd, 1);
832 EnterCriticalSection (&data->io_lock);
833 if (data->sock_to_state == NULL) {
834 LeaveCriticalSection (&data->io_lock);
838 /* FIXME: 64 bit issue: handle can be a pointer on windows? */
839 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (state->handle));
841 list = mono_mlist_alloc ((MonoObject*)state);
843 list = mono_mlist_append (list, (MonoObject*)state);
846 events = get_events_from_list (list);
847 INIT_POLLFD (data->newpfd, GPOINTER_TO_INT (state->handle), events);
848 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (state->handle), list);
849 LeaveCriticalSection (&data->io_lock);
850 *msg = (char) state->operation;
852 w = write (data->pipe [1], msg, 1);
855 send ((SOCKET) data->pipe [1], msg, 1, 0);
861 socket_io_add_epoll (MonoSocketAsyncResult *state)
864 SocketIOData *data = &socket_io_data;
865 struct epoll_event event;
869 if (mono_runtime_is_shutting_down () || data->inited == 3 || data->sock_to_state == NULL)
872 memset (&event, 0, sizeof (struct epoll_event));
873 fd = GPOINTER_TO_INT (state->handle);
874 EnterCriticalSection (&data->io_lock);
875 if (data->sock_to_state == NULL) {
876 LeaveCriticalSection (&data->io_lock);
879 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
881 list = mono_mlist_alloc ((MonoObject*)state);
882 epoll_op = EPOLL_CTL_ADD;
884 list = mono_mlist_append (list, (MonoObject*)state);
885 epoll_op = EPOLL_CTL_MOD;
888 ievt = get_events_from_list (list);
889 if ((ievt & MONO_POLLIN) != 0)
890 event.events |= EPOLLIN;
891 if ((ievt & MONO_POLLOUT) != 0)
892 event.events |= EPOLLOUT;
894 mono_g_hash_table_replace (data->sock_to_state, state->handle, list);
896 EPOLL_DEBUG ("%s %d with %d", epoll_op == EPOLL_CTL_ADD ? "ADD" : "MOD", fd, event.events);
897 if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
899 if (epoll_op == EPOLL_CTL_ADD && err == EEXIST) {
900 epoll_op = EPOLL_CTL_MOD;
901 if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
902 g_message ("epoll_ctl(MOD): %d %s", err, g_strerror (err));
906 LeaveCriticalSection (&data->io_lock);
913 socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
915 if (async_tp.pool_status == 2 || mono_runtime_is_shutting_down ())
918 socket_io_init (&socket_io_data);
920 MONO_OBJECT_SETREF (state, ares, ares);
922 if (socket_io_data.epoll_disabled == FALSE) {
923 if (socket_io_add_epoll (state))
927 socket_io_add_poll (state);
930 #ifndef DISABLE_SOCKETS
932 socket_io_filter (MonoObject *target, MonoObject *state)
935 MonoSocketAsyncResult *sock_res = (MonoSocketAsyncResult *) state;
938 if (target == NULL || state == NULL)
941 if (socket_async_call_klass == NULL) {
942 klass = target->vtable->klass;
943 /* Check if it's SocketAsyncCall in System.Net.Sockets
944 * FIXME: check the assembly is signed correctly for extra care
946 if (klass->name [0] == 'S' && strcmp (klass->name, "SocketAsyncCall") == 0
947 && strcmp (mono_image_get_name (klass->image), "System") == 0
948 && klass->nested_in && strcmp (klass->nested_in->name, "Socket") == 0)
949 socket_async_call_klass = klass;
952 if (process_async_call_klass == NULL) {
953 klass = target->vtable->klass;
954 /* Check if it's AsyncReadHandler in System.Diagnostics.Process
955 * FIXME: check the assembly is signed correctly for extra care
957 if (klass->name [0] == 'A' && strcmp (klass->name, "AsyncReadHandler") == 0
958 && strcmp (mono_image_get_name (klass->image), "System") == 0
959 && klass->nested_in && strcmp (klass->nested_in->name, "Process") == 0)
960 process_async_call_klass = klass;
962 /* return both when socket_async_call_klass has not been seen yet and when
963 * the object is not an instance of the class.
965 if (target->vtable->klass != socket_async_call_klass && target->vtable->klass != process_async_call_klass)
968 op = sock_res->operation;
969 if (op < AIO_OP_FIRST || op >= AIO_OP_LAST)
974 #endif /* !DISABLE_SOCKETS */
976 /* Returns the exception thrown when invoking, if any */
978 mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares)
980 ASyncCall *ac = (ASyncCall *)ares->object_data;
981 MonoObject *res, *exc = NULL;
982 MonoArray *out_args = NULL;
983 HANDLE wait_event = NULL;
985 if (ares->execution_context) {
986 /* use captured ExecutionContext (if available) */
987 MONO_OBJECT_SETREF (ares, original_context, mono_thread_get_execution_context ());
988 mono_thread_set_execution_context (ares->execution_context);
990 ares->original_context = NULL;
994 /* Fast path from ThreadPool.*QueueUserWorkItem */
995 void *pa = ares->async_state;
996 mono_runtime_delegate_invoke (ares->async_delegate, &pa, &exc);
998 MonoObject *cb_exc = NULL;
1000 ac->msg->exc = NULL;
1001 res = mono_message_invoke (ares->async_delegate, ac->msg, &exc, &out_args);
1002 MONO_OBJECT_SETREF (ac, res, res);
1003 MONO_OBJECT_SETREF (ac, msg->exc, exc);
1004 MONO_OBJECT_SETREF (ac, out_args, out_args);
1006 mono_monitor_enter ((MonoObject *) ares);
1007 ares->completed = 1;
1008 if (ares->handle != NULL)
1009 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
1010 mono_monitor_exit ((MonoObject *) ares);
1011 /* notify listeners */
1012 if (wait_event != NULL)
1013 SetEvent (wait_event);
1015 /* call async callback if cb_method != null*/
1016 if (ac != NULL && ac->cb_method) {
1019 mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &cb_exc);
1020 MONO_OBJECT_SETREF (ac->msg, exc, cb_exc);
1027 /* restore original thread execution context if flow isn't suppressed, i.e. non null */
1028 if (ares->original_context) {
1029 mono_thread_set_execution_context (ares->original_context);
1030 ares->original_context = NULL;
1036 threadpool_start_idle_threads (ThreadPool *tp)
1040 if (tp->pool_status == 1 && !tp->is_io)
1041 mono_thread_create_internal (mono_get_root_domain (), monitor_thread, tp, TRUE);
1045 if (n >= tp->min_threads)
1047 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n)
1050 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
1051 mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE);
1052 SleepEx (100, TRUE);
1057 threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer))
1059 memset (tp, 0, sizeof (ThreadPool));
1060 MONO_SEM_INIT (&tp->lock, 1);
1061 tp->min_threads = min_threads;
1062 tp->max_threads = max_threads;
1063 tp->async_invoke = async_invoke;
1064 MONO_SEM_INIT (&tp->new_job, 0);
1068 init_perf_counter (const char *category, const char *counter)
1070 MonoString *category_str;
1071 MonoString *counter_str;
1072 MonoString *machine;
1077 if (category == NULL || counter == NULL)
1079 root = mono_get_root_domain ();
1080 category_str = mono_string_new (root, category);
1081 counter_str = mono_string_new (root, counter);
1082 machine = mono_string_new (root, ".");
1083 return mono_perfcounter_get_impl (category_str, counter_str, NULL, machine, &type, &custom);
1088 print_pool_info (ThreadPool *tp)
1091 // if (tp->tail - tp->head == 0)
1094 g_print ("Pool status? %d\n", InterlockedCompareExchange (&tp->pool_status, 0, 0));
1095 g_print ("Min. threads: %d\n", InterlockedCompareExchange (&tp->min_threads, 0, 0));
1096 g_print ("Max. threads: %d\n", InterlockedCompareExchange (&tp->max_threads, 0, 0));
1097 g_print ("nthreads: %d\n", InterlockedCompareExchange (&tp->nthreads, 0, 0));
1098 g_print ("busy threads: %d\n", InterlockedCompareExchange (&tp->busy_threads, 0, 0));
1099 g_print ("Waiting: %d\n", InterlockedCompareExchange (&tp->waiting, 0, 0));
1100 g_print ("Queued: %d\n", (tp->tail - tp->head));
1101 if (tp == &async_tp) {
1103 EnterCriticalSection (&wsqs_lock);
1104 for (i = 0; i < wsqs->len; i++) {
1105 g_print ("\tWSQ %d: %d\n", i, mono_wsq_count (g_ptr_array_index (wsqs, i)));
1107 LeaveCriticalSection (&wsqs_lock);
1109 g_print ("\tSockets: %d\n", mono_g_hash_table_size (socket_io_data.sock_to_state));
1111 g_print ("-------------\n");
1115 signal_handler (int signo)
1120 MONO_SEM_WAIT (&tp->lock);
1121 g_print ("\n-----Non-IO-----\n");
1122 print_pool_info (tp);
1123 MONO_SEM_POST (&tp->lock);
1125 MONO_SEM_WAIT (&tp->lock);
1126 g_print ("\n-----IO-----\n");
1127 print_pool_info (tp);
1128 MONO_SEM_POST (&tp->lock);
1134 monitor_thread (gpointer data)
1137 MonoInternalThread *thread;
1143 thread = mono_thread_internal_current ();
1148 ts = mono_msec_ticks ();
1149 if (SleepEx (ms, TRUE) == 0)
1151 ms -= (mono_msec_ticks () - ts);
1152 if (mono_runtime_is_shutting_down ())
1154 if (THREAD_WANTS_A_BREAK (thread))
1155 mono_thread_interruption_checkpoint ();
1158 if (mono_runtime_is_shutting_down ())
1160 if (tp->waiting > 0)
1162 MONO_SEM_WAIT (&tp->lock);
1163 need_one = (tp->head != tp->tail);
1165 EnterCriticalSection (&wsqs_lock);
1166 for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
1168 wsq = g_ptr_array_index (wsqs, i);
1169 if (mono_wsq_count (wsq) > 0) {
1174 LeaveCriticalSection (&wsqs_lock);
1176 MONO_SEM_POST (&tp->lock);
1178 threadpool_start_thread (tp);
1183 mono_thread_pool_init ()
1185 gint threads_per_cpu = 1;
1187 gint cpu_count = mono_cpu_count ();
1193 result = InterlockedCompareExchange (&tp_inited, 1, 0);
1202 MONO_GC_REGISTER_ROOT (async_tp.first);
1203 MONO_GC_REGISTER_ROOT (async_tp.last);
1204 MONO_GC_REGISTER_ROOT (async_tp.unused);
1205 MONO_GC_REGISTER_ROOT (async_io_tp.first);
1206 MONO_GC_REGISTER_ROOT (async_io_tp.unused);
1207 MONO_GC_REGISTER_ROOT (async_io_tp.last);
1209 MONO_GC_REGISTER_ROOT (socket_io_data.sock_to_state);
1210 InitializeCriticalSection (&socket_io_data.io_lock);
1211 if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
1212 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
1213 if (threads_per_cpu < 1)
1214 threads_per_cpu = 1;
1217 thread_count = MIN (cpu_count * threads_per_cpu, 100 * cpu_count);
1218 threadpool_init (&async_tp, thread_count, MAX (100 * cpu_count, thread_count), async_invoke_thread);
1219 threadpool_init (&async_io_tp, cpu_count * 2, cpu_count * 4, async_invoke_thread);
1220 async_io_tp.is_io = TRUE;
1222 async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
1223 g_assert (async_call_klass);
1225 InitializeCriticalSection (&wsqs_lock);
1226 wsqs = g_ptr_array_sized_new (MAX (100 * cpu_count, thread_count));
1229 async_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "Work Items Added");
1230 g_assert (async_tp.pc_nitems);
1232 async_io_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "IO Work Items Added");
1233 g_assert (async_io_tp.pc_nitems);
1235 async_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of Threads");
1236 g_assert (async_tp.pc_nthreads);
1238 async_io_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of IO Threads");
1239 g_assert (async_io_tp.pc_nthreads);
1242 signal (SIGALRM, signal_handler);
1248 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
1251 MonoDomain *domain = mono_domain_get ();
1252 MonoAsyncResult *ares;
1255 ac = (ASyncCall*)mono_object_new (domain, async_call_klass);
1256 MONO_OBJECT_SETREF (ac, msg, msg);
1257 MONO_OBJECT_SETREF (ac, state, state);
1259 if (async_callback) {
1260 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
1261 MONO_OBJECT_SETREF (ac, cb_target, async_callback);
1264 ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
1265 MONO_OBJECT_SETREF (ares, async_delegate, target);
1267 #ifndef DISABLE_SOCKETS
1268 if (socket_io_filter (target, state)) {
1269 socket_io_add (ares, (MonoSocketAsyncResult *) state);
1273 threadpool_append_job (&async_tp, (MonoObject *) ares);
1278 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1286 /* check if already finished */
1287 mono_monitor_enter ((MonoObject *) ares);
1289 if (ares->endinvoke_called) {
1290 *exc = (MonoObject *) mono_get_exception_invalid_operation (NULL);
1291 mono_monitor_exit ((MonoObject *) ares);
1295 ares->endinvoke_called = 1;
1296 /* wait until we are really finished */
1297 if (!ares->completed) {
1298 if (ares->handle == NULL) {
1299 wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1300 g_assert(wait_event != 0);
1301 MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), wait_event));
1303 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
1305 mono_monitor_exit ((MonoObject *) ares);
1306 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
1308 mono_monitor_exit ((MonoObject *) ares);
1311 ac = (ASyncCall *) ares->object_data;
1312 g_assert (ac != NULL);
1313 *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1314 *out_args = ac->out_args;
1320 threadpool_kill_idle_threads (ThreadPool *tp)
1324 n = (gint) InterlockedCompareExchange (&tp->max_threads, 0, -1);
1327 MONO_SEM_POST (&tp->new_job);
1332 mono_thread_pool_cleanup (void)
1334 if (async_tp.pool_status == 0 || async_tp.pool_status == 2)
1337 if (async_tp.pool_status == 1 && InterlockedCompareExchange (&async_tp.pool_status, 2, 1) == 2)
1340 InterlockedExchange (&async_io_tp.pool_status, 2);
1341 MONO_SEM_WAIT (&async_tp.lock);
1342 threadpool_free_queue (&async_tp);
1343 threadpool_kill_idle_threads (&async_tp);
1344 MONO_SEM_POST (&async_tp.lock);
1346 socket_io_cleanup (&socket_io_data); /* Empty when DISABLE_SOCKETS is defined */
1347 MONO_SEM_WAIT (&async_io_tp.lock);
1348 threadpool_free_queue (&async_io_tp);
1349 threadpool_kill_idle_threads (&async_io_tp);
1350 MONO_SEM_POST (&async_io_tp.lock);
1351 MONO_SEM_DESTROY (&async_io_tp.new_job);
1353 EnterCriticalSection (&wsqs_lock);
1354 mono_wsq_cleanup ();
1356 g_ptr_array_free (wsqs, TRUE);
1358 LeaveCriticalSection (&wsqs_lock);
1359 MONO_SEM_DESTROY (&async_tp.new_job);
1362 /* Caller must enter &tp->lock */
1364 dequeue_job_nolock (ThreadPool *tp)
1372 if (mono_runtime_is_shutting_down ())
1374 if (!list || tp->head == tp->tail)
1377 array = (MonoArray *) mono_mlist_get_data (list);
1378 ar = mono_array_get (array, MonoObject *, tp->head % QUEUE_LENGTH);
1379 mono_array_set (array, MonoObject *, tp->head % QUEUE_LENGTH, NULL);
1381 if ((tp->head % QUEUE_LENGTH) == 0) {
1383 tp->first = mono_mlist_next (list);
1384 if (tp->first == NULL)
1386 if (mono_mlist_length (tp->unused) < 20) {
1387 /* reuse this chunk */
1388 tp->unused = mono_mlist_set_next (list, tp->unused);
1390 tp->head -= QUEUE_LENGTH;
1391 tp->tail -= QUEUE_LENGTH;
1394 } while (ar == NULL);
1399 threadpool_start_thread (ThreadPool *tp)
1403 while (!mono_runtime_is_shutting_down () && (n = tp->nthreads) < tp->max_threads) {
1404 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n) {
1405 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
1406 mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE);
1415 pulse_on_new_job (ThreadPool *tp)
1418 MONO_SEM_POST (&tp->new_job);
1422 icall_append_job (MonoObject *ar)
1424 threadpool_append_job (&async_tp, ar);
1428 threadpool_append_job (ThreadPool *tp, MonoObject *ar)
1430 threadpool_append_jobs (tp, &ar, 1);
1434 create_or_reuse_list (ThreadPool *tp)
1442 tp->unused = mono_mlist_next (list);
1443 mono_mlist_set_next (list, NULL);
1444 //TP_DEBUG (tp->nodes_reused++);
1446 array = mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, QUEUE_LENGTH);
1447 list = mono_mlist_alloc ((MonoObject *) array);
1448 //TP_DEBUG (tp->nodes_created++);
1454 threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs)
1456 static int job_counter;
1461 gboolean lock_taken = FALSE; /* We won't take the lock when the local queue is used */
1463 if (mono_runtime_is_shutting_down ())
1466 if (tp->pool_status == 0 && InterlockedCompareExchange (&tp->pool_status, 1, 0) == 0)
1467 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, tp, TRUE);
1469 for (i = 0; i < njobs; i++) {
1471 if (ar == NULL || mono_domain_is_unloading (ar->vtable->domain))
1472 continue; /* Might happen when cleaning domain jobs */
1473 if (!tp->is_io && (InterlockedIncrement (&job_counter) % 10) == 0) {
1474 MonoAsyncResult *o = (MonoAsyncResult *) ar;
1475 o->add_time = mono_100ns_ticks ();
1477 threadpool_jobs_inc (ar);
1478 mono_perfcounter_update_value (tp->pc_nitems, TRUE, 1);
1479 if (!tp->is_io && mono_wsq_local_push (ar))
1483 MONO_SEM_WAIT (&tp->lock);
1486 if ((tp->tail % QUEUE_LENGTH) == 0) {
1487 list = create_or_reuse_list (tp);
1488 if (tp->last != NULL)
1489 mono_mlist_set_next (tp->last, list);
1491 if (tp->first == NULL)
1492 tp->first = tp->last;
1495 array = (MonoArray *) mono_mlist_get_data (tp->last);
1496 mono_array_setref (array, tp->tail % QUEUE_LENGTH, ar);
1500 MONO_SEM_POST (&tp->lock);
1502 for (i = 0; i < MIN(njobs, tp->max_threads); i++)
1503 pulse_on_new_job (tp);
1507 threadpool_clear_queue (ThreadPool *tp, MonoDomain *domain)
1516 MONO_SEM_WAIT (&tp->lock);
1517 current = tp->first;
1519 array = (MonoArray *) mono_mlist_get_data (current);
1520 for (i = 0; i < QUEUE_LENGTH; i++) {
1521 obj = mono_array_get (array, MonoObject*, i);
1522 if (obj != NULL && obj->vtable->domain == domain) {
1524 mono_array_setref (array, i, NULL);
1525 threadpool_jobs_dec (obj);
1528 current = mono_mlist_next (current);
1531 if (!domain_count) {
1532 MONO_SEM_POST (&tp->lock);
1536 current = tp->first;
1541 MONO_SEM_POST (&tp->lock);
1542 /* Re-add everything but the nullified elements */
1544 array = (MonoArray *) mono_mlist_get_data (current);
1545 threadpool_append_jobs (tp, mono_array_addr (array, MonoObject *, 0), QUEUE_LENGTH);
1546 memset (mono_array_addr (array, MonoObject *, 0), 0, sizeof (MonoObject *) * QUEUE_LENGTH);
1547 current = mono_mlist_next (current);
1552 * Clean up the threadpool of all domain jobs.
1553 * Can only be called as part of the domain unloading process as
1554 * it will wait for all jobs to be visible to the interruption code.
1557 mono_thread_pool_remove_domain_jobs (MonoDomain *domain, int timeout)
1561 guint32 start_time = 0;
1563 g_assert (domain->state == MONO_APPDOMAIN_UNLOADING);
1565 threadpool_clear_queue (&async_tp, domain);
1566 threadpool_clear_queue (&async_io_tp, domain);
1569 * There might be some threads out that could be about to execute stuff from the given domain.
1570 * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
1572 sem_handle = CreateSemaphore (NULL, 0, 1, NULL);
1574 domain->cleanup_semaphore = sem_handle;
1576 * The memory barrier here is required to have global ordering between assigning to cleanup_semaphone
1577 * and reading threadpool_jobs.
1578 * Otherwise this thread could read a stale version of threadpool_jobs and wait forever.
1580 mono_memory_write_barrier ();
1582 if (domain->threadpool_jobs && timeout != -1)
1583 start_time = mono_msec_ticks ();
1584 while (domain->threadpool_jobs) {
1585 WaitForSingleObject (sem_handle, timeout);
1586 if (timeout != -1 && (mono_msec_ticks () - start_time) > timeout) {
1592 domain->cleanup_semaphore = NULL;
1593 CloseHandle (sem_handle);
1598 threadpool_free_queue (ThreadPool *tp)
1600 tp->head = tp->tail = 0;
1606 mono_thread_pool_is_queue_array (MonoArray *o)
1610 // FIXME: need some fix in sgen code.
1611 // There are roots at: async*tp.unused (MonoMList) and wsqs [n]->queue (MonoArray)
1612 return obj == async_tp.first || obj == async_io_tp.first;
1616 add_wsq (MonoWSQ *wsq)
1623 EnterCriticalSection (&wsqs_lock);
1625 LeaveCriticalSection (&wsqs_lock);
1628 for (i = 0; i < wsqs->len; i++) {
1629 if (g_ptr_array_index (wsqs, i) == NULL) {
1630 wsqs->pdata [i] = wsq;
1631 LeaveCriticalSection (&wsqs_lock);
1635 g_ptr_array_add (wsqs, wsq);
1636 LeaveCriticalSection (&wsqs_lock);
1640 remove_wsq (MonoWSQ *wsq)
1645 EnterCriticalSection (&wsqs_lock);
1647 LeaveCriticalSection (&wsqs_lock);
1650 g_ptr_array_remove_fast (wsqs, wsq);
1651 LeaveCriticalSection (&wsqs_lock);
1655 try_steal (gpointer *data, gboolean retry)
1660 if (wsqs == NULL || data == NULL || *data != NULL)
1665 if (mono_runtime_is_shutting_down ())
1667 for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
1668 if (mono_runtime_is_shutting_down ()) {
1671 mono_wsq_try_steal (wsqs->pdata [i], data, ms);
1672 if (*data != NULL) {
1677 } while (retry && ms < 11);
1681 dequeue_or_steal (ThreadPool *tp, gpointer *data)
1683 if (mono_runtime_is_shutting_down ())
1685 TP_DEBUG ("Dequeue");
1686 MONO_SEM_WAIT (&tp->lock);
1687 *data = dequeue_job_nolock (tp);
1688 MONO_SEM_POST (&tp->lock);
1689 if (!tp->is_io && !*data)
1690 try_steal (data, FALSE);
1691 return (*data != NULL);
1695 process_idle_times (ThreadPool *tp, gint64 t)
1699 gboolean compute_avg;
1703 if (tp->ignore_times || t <= 0)
1706 compute_avg = FALSE;
1707 ticks = mono_100ns_ticks ();
1709 SPIN_LOCK (tp->sp_lock);
1710 if (tp->ignore_times) {
1711 SPIN_UNLOCK (tp->sp_lock);
1716 if (tp->last_check == 0)
1717 tp->last_check = ticks;
1718 else if (tp->last_check > 0 && (ticks - tp->last_check) > 5000000) {
1719 tp->ignore_times = 1;
1722 SPIN_UNLOCK (tp->sp_lock);
1727 //printf ("Items: %d Time elapsed: %.3fs\n", tp->n_sum, (ticks - tp->last_check) / 10000.0);
1728 tp->last_check = ticks;
1730 avg = tp->time_sum / tp->n_sum;
1731 if (tp->averages [1] == 0) {
1732 tp->averages [1] = avg;
1734 per1 = ((100 * (ABS (avg - tp->averages [1]))) / tp->averages [1]);
1736 if (avg > tp->averages [1]) {
1737 if (tp->averages [1] < tp->averages [0]) {
1742 } else if (avg < tp->averages [1] && tp->averages [1] < tp->averages [0]) {
1747 min = tp->min_threads;
1749 if ((n - min) < min && tp->busy_threads == n)
1753 if (new_threads != 0) {
1754 printf ("n: %d per1: %lld avg=%lld avg1=%lld avg0=%lld\n", new_threads, per1, avg, tp->averages [1], tp->averages [0]);
1762 tp->averages [0] = tp->averages [1];
1763 tp->averages [1] = avg;
1764 tp->ignore_times = 0;
1766 if (new_threads == -1) {
1767 if (tp->destroy_thread == 0 && InterlockedCompareExchange (&tp->destroy_thread, 1, 0) == 0)
1768 pulse_on_new_job (tp);
1773 should_i_die (ThreadPool *tp)
1775 gboolean result = FALSE;
1776 if (tp->destroy_thread == 1 && InterlockedCompareExchange (&tp->destroy_thread, 0, 1) == 1)
1777 result = (tp->nthreads > tp->min_threads);
1782 async_invoke_thread (gpointer data)
1785 MonoInternalThread *thread;
1793 wsq = mono_wsq_create ();
1797 thread = mono_thread_internal_current ();
1799 tp_start_func (tp_hooks_user_data);
1802 MonoAsyncResult *ar;
1803 gboolean is_io_task;
1807 ar = (MonoAsyncResult *) data;
1809 InterlockedIncrement (&tp->busy_threads);
1810 #ifndef DISABLE_SOCKETS
1811 is_io_task = (strcmp (((MonoObject *) data)->vtable->klass->name, "AsyncResult"));
1813 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1815 switch (state->operation) {
1816 case AIO_OP_RECEIVE:
1817 state->total = ICALL_RECV (state);
1820 state->total = ICALL_SEND (state);
1825 /* worker threads invokes methods in different domains,
1826 * so we need to set the right domain here */
1827 domain = ((MonoObject *)ar)->vtable->domain;
1830 if (mono_domain_is_unloading (domain) || mono_runtime_is_shutting_down ()) {
1831 threadpool_jobs_dec ((MonoObject *)ar);
1834 InterlockedDecrement (&tp->busy_threads);
1836 mono_thread_push_appdomain_ref (domain);
1837 if (threadpool_jobs_dec ((MonoObject *)ar)) {
1840 mono_thread_pop_appdomain_ref ();
1841 InterlockedDecrement (&tp->busy_threads);
1845 if (mono_domain_set (domain, FALSE)) {
1848 if (tp_item_begin_func)
1849 tp_item_begin_func (tp_item_user_data);
1851 if (!is_io_task && ar->add_time > 0)
1852 process_idle_times (tp, ar->add_time);
1853 exc = mono_async_invoke (tp, ar);
1854 if (tp_item_end_func)
1855 tp_item_end_func (tp_item_user_data);
1856 if (exc && mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_CURRENT) {
1857 mono_unhandled_exception (exc);
1860 mono_domain_set (mono_get_root_domain (), TRUE);
1862 mono_thread_pop_appdomain_ref ();
1863 InterlockedDecrement (&tp->busy_threads);
1864 /* If the callee changes the background status, set it back to TRUE */
1865 if (!mono_thread_test_state (thread , ThreadState_Background))
1866 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
1872 must_die = should_i_die (tp);
1873 TP_DEBUG ("Trying to get a job");
1874 if (!must_die && (tp->is_io || !mono_wsq_local_pop (&data)))
1875 dequeue_or_steal (tp, &data);
1876 TP_DEBUG ("Done trying to get a job %p", data);
1879 while (!must_die && !data && n_naps < 4) {
1882 TP_DEBUG ("Waiting");
1883 InterlockedIncrement (&tp->waiting);
1884 #if defined(__OpenBSD__)
1885 while ((res = mono_sem_wait (&tp->new_job, TRUE)) == -1) {// && errno == EINTR) {
1887 while ((res = mono_sem_timedwait (&tp->new_job, 2000, TRUE)) == -1) {// && errno == EINTR) {
1889 if (mono_runtime_is_shutting_down ())
1891 if (THREAD_WANTS_A_BREAK (thread))
1892 mono_thread_interruption_checkpoint ();
1894 TP_DEBUG ("Done waiting");
1895 InterlockedDecrement (&tp->waiting);
1896 if (mono_runtime_is_shutting_down ())
1898 must_die = should_i_die (tp);
1899 dequeue_or_steal (tp, &data);
1903 if (!data && tp->is_io && !mono_runtime_is_shutting_down ()) {
1904 mono_wsq_local_pop (&data);
1905 if (data && must_die) {
1906 InterlockedCompareExchange (&tp->destroy_thread, 1, 0);
1907 pulse_on_new_job (tp);
1916 down = mono_runtime_is_shutting_down ();
1917 if (!down && nt <= tp->min_threads)
1919 if (down || InterlockedCompareExchange (&tp->nthreads, nt - 1, nt) == nt) {
1920 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, -1);
1924 while (mono_wsq_local_pop (&data)) {
1925 threadpool_jobs_dec (data);
1928 mono_wsq_destroy (wsq);
1931 tp_finish_func (tp_hooks_user_data);
1938 g_assert_not_reached ();
1942 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
1944 *workerThreads = async_tp.max_threads - async_tp.busy_threads;
1945 *completionPortThreads = async_io_tp.max_threads - async_io_tp.busy_threads;
1949 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
1951 *workerThreads = async_tp.max_threads;
1952 *completionPortThreads = async_io_tp.max_threads;
1956 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
1958 *workerThreads = async_tp.min_threads;
1959 *completionPortThreads = async_io_tp.min_threads;
1963 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
1966 gint max_io_threads;
1968 max_threads = async_tp.max_threads;
1969 if (workerThreads <= 0 || workerThreads > max_threads)
1972 max_io_threads = async_io_tp.max_threads;
1973 if (completionPortThreads <= 0 || completionPortThreads > max_io_threads)
1976 InterlockedExchange (&async_tp.min_threads, workerThreads);
1977 InterlockedExchange (&async_io_tp.min_threads, completionPortThreads);
1978 if (workerThreads > async_tp.nthreads)
1979 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_tp, TRUE);
1980 if (completionPortThreads > async_io_tp.nthreads)
1981 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_io_tp, TRUE);
1986 ves_icall_System_Threading_ThreadPool_SetMaxThreads (gint workerThreads, gint completionPortThreads)
1989 gint min_io_threads;
1992 cpu_count = mono_cpu_count ();
1993 min_threads = async_tp.min_threads;
1994 if (workerThreads < min_threads || workerThreads < cpu_count)
1997 /* We don't really have the concept of completion ports. Do we care here? */
1998 min_io_threads = async_io_tp.min_threads;
1999 if (completionPortThreads < min_io_threads || completionPortThreads < cpu_count)
2002 InterlockedExchange (&async_tp.max_threads, workerThreads);
2003 InterlockedExchange (&async_io_tp.max_threads, completionPortThreads);
2008 * mono_install_threadpool_thread_hooks
2009 * @start_func: the function to be called right after a new threadpool thread is created. Can be NULL.
2010 * @finish_func: the function to be called right before a thredpool thread is exiting. Can be NULL.
2011 * @user_data: argument passed to @start_func and @finish_func.
2013 * @start_fun will be called right after a threadpool thread is created and @finish_func right before a threadpool thread exits.
2014 * The calls will be made from the thread itself.
2017 mono_install_threadpool_thread_hooks (MonoThreadPoolFunc start_func, MonoThreadPoolFunc finish_func, gpointer user_data)
2019 tp_start_func = start_func;
2020 tp_finish_func = finish_func;
2021 tp_hooks_user_data = user_data;
2025 * mono_install_threadpool_item_hooks
2026 * @begin_func: the function to be called before a threadpool work item processing starts.
2027 * @end_func: the function to be called after a threadpool work item is finished.
2028 * @user_data: argument passed to @begin_func and @end_func.
2030 * The calls will be made from the thread itself and from the same AppDomain
2031 * where the work item was executed.
2035 mono_install_threadpool_item_hooks (MonoThreadPoolItemFunc begin_func, MonoThreadPoolItemFunc end_func, gpointer user_data)
2037 tp_item_begin_func = begin_func;
2038 tp_item_end_func = end_func;
2039 tp_item_user_data = user_data;