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,
216 get_socket_assembly (void)
218 static const char *version = NULL;
219 static gboolean moonlight;
220 static MonoImage *socket_assembly = NULL;
222 if (version == NULL) {
223 version = mono_get_runtime_info ()->framework_version;
224 moonlight = !strcmp (version, "2.1");
227 if (socket_assembly == NULL)
228 socket_assembly = mono_image_loaded (moonlight ? "System.Net" : "System");
230 return socket_assembly;
234 * Note that we call it is_socket_type() where 'socket' refers to the image
235 * that contains the System.Net.Sockets.Socket type.
238 is_socket_type (MonoClass *klass)
240 return klass->image == get_socket_assembly ();
244 is_system_type (MonoClass *klass)
246 static MonoImage *system_image = NULL;
248 if (system_image == NULL)
249 system_image = mono_image_loaded ("System");
251 return klass->image == system_image;
255 is_corlib_type (MonoClass *klass)
257 return klass->image == mono_defaults.corlib;
260 #define check_type_cached(ASSEMBLY, _class, _namespace, _name) do { \
261 static MonoClass *cached_class; \
263 return cached_class == _class; \
264 if (is_##ASSEMBLY##_type (_class) && !strcmp (_name, _class->name) && !strcmp (_namespace, _class->name_space)) { \
265 cached_class = _class; \
271 #define check_corlib_type_cached(_class, _namespace, _name) check_type_cached (corlib, _class, _namespace, _name)
273 #define check_socket_type_cached(_class, _namespace, _name) check_type_cached (socket, _class, _namespace, _name)
275 #define check_system_type_cached(_class, _namespace, _name) check_type_cached (system, _class, _namespace, _name)
278 is_corlib_asyncresult (MonoClass *klass)
280 check_corlib_type_cached (klass, "System.Runtime.Remoting.Messaging", "AsyncResult");
284 is_socket (MonoClass *klass)
286 check_socket_type_cached (klass, "System.Net.Sockets", "Socket");
290 is_socketasyncresult (MonoClass *klass)
292 return (klass->nested_in &&
293 is_socket (klass->nested_in) &&
294 !strcmp (klass->name, "SocketAsyncResult"));
298 is_socketasynccall (MonoClass *klass)
300 return (klass->nested_in &&
301 is_socket (klass->nested_in) &&
302 !strcmp (klass->name, "SocketAsyncCall"));
306 is_appdomainunloaded_exception (MonoClass *klass)
308 check_corlib_type_cached (klass, "System", "AppDomainUnloadedException");
312 is_sd_process (MonoClass *klass)
314 check_system_type_cached (klass, "System.Diagnostics", "Process");
318 is_sdp_asyncreadhandler (MonoClass *klass)
321 return (klass->nested_in &&
322 is_sd_process (klass->nested_in) &&
323 !strcmp (klass->name, "AsyncReadHandler"));
327 #ifdef DISABLE_SOCKETS
329 #define socket_io_cleanup(x)
332 get_event_from_state (MonoSocketAsyncResult *state)
334 g_assert_not_reached ();
339 get_events_from_list (MonoMList *list)
347 socket_io_cleanup (SocketIOData *data)
349 EnterCriticalSection (&data->io_lock);
350 if (data->inited != 2) {
351 LeaveCriticalSection (&data->io_lock);
357 closesocket (data->pipe [0]);
358 closesocket (data->pipe [1]);
360 if (data->pipe [0] > -1)
361 close (data->pipe [0]);
362 if (data->pipe [1] > -1)
363 close (data->pipe [1]);
368 CloseHandle (data->new_sem);
369 data->new_sem = NULL;
370 mono_g_hash_table_destroy (data->sock_to_state);
371 data->sock_to_state = NULL;
372 g_free (data->newpfd);
375 if (FALSE == data->epoll_disabled)
376 close (data->epollfd);
378 LeaveCriticalSection (&data->io_lock);
382 get_event_from_state (MonoSocketAsyncResult *state)
384 switch (state->operation) {
387 case AIO_OP_RECV_JUST_CALLBACK:
388 case AIO_OP_RECEIVEFROM:
389 case AIO_OP_READPIPE:
390 case AIO_OP_ACCEPTRECEIVE:
391 case AIO_OP_RECEIVE_BUFFERS:
394 case AIO_OP_SEND_JUST_CALLBACK:
397 case AIO_OP_SEND_BUFFERS:
398 case AIO_OP_DISCONNECT:
400 default: /* Should never happen */
401 g_message ("get_event_from_state: unknown value in switch!!!");
407 get_events_from_list (MonoMList *list)
409 MonoSocketAsyncResult *state;
412 while (list && (state = (MonoSocketAsyncResult *)mono_mlist_get_data (list))) {
413 events |= get_event_from_state (state);
414 list = mono_mlist_next (list);
420 #define ICALL_RECV(x) ves_icall_System_Net_Sockets_Socket_Receive_internal (\
421 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
422 x->socket_flags, &x->error);
424 #define ICALL_SEND(x) ves_icall_System_Net_Sockets_Socket_Send_internal (\
425 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
426 x->socket_flags, &x->error);
428 #endif /* !DISABLE_SOCKETS */
431 threadpool_jobs_inc (MonoObject *obj)
434 InterlockedIncrement (&obj->vtable->domain->threadpool_jobs);
438 threadpool_jobs_dec (MonoObject *obj)
440 MonoDomain *domain = obj->vtable->domain;
441 int remaining_jobs = InterlockedDecrement (&domain->threadpool_jobs);
442 if (remaining_jobs == 0 && domain->cleanup_semaphore) {
443 ReleaseSemaphore (domain->cleanup_semaphore, 1, NULL);
451 get_io_event (MonoMList **list, gint event)
461 state = mono_mlist_get_data (current);
462 if (get_event_from_state ((MonoSocketAsyncResult *) state) == event)
467 current = mono_mlist_next (current);
472 mono_mlist_set_next (prev, mono_mlist_next (current));
474 *list = mono_mlist_next (*list);
483 process_io_event (MonoMList *list, int event)
485 MonoSocketAsyncResult *state;
491 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
492 if (get_event_from_state (state) == event)
495 list = mono_mlist_next (list);
499 oldlist = mono_mlist_remove_item (oldlist, list);
500 EPOLL_DEBUG ("Dispatching event %d on socket %p", event, state->handle);
501 threadpool_append_job (&async_io_tp, (MonoObject *) state);
508 mark_bad_fds (mono_pollfd *pfds, int nfds)
514 for (i = 0; i < nfds; i++) {
519 ret = mono_poll (pfd, 1, 0);
520 if (ret == -1 && errno == EBADF) {
521 pfd->revents |= MONO_POLLNVAL;
523 } else if (ret == 1) {
532 socket_io_poll_main (gpointer p)
534 #if MONO_SMALL_CONFIG
535 #define INITIAL_POLLFD_SIZE 128
537 #define INITIAL_POLLFD_SIZE 1024
539 #define POLL_ERRORS (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL)
540 SocketIOData *data = p;
545 MonoInternalThread *thread;
547 thread = mono_thread_internal_current ();
549 allocated = INITIAL_POLLFD_SIZE;
550 pfds = g_new0 (mono_pollfd, allocated);
551 INIT_POLLFD (pfds, data->pipe [0], MONO_POLLIN);
552 for (i = 1; i < allocated; i++)
553 INIT_POLLFD (&pfds [i], -1, 0);
563 if (THREAD_WANTS_A_BREAK (thread))
564 mono_thread_interruption_checkpoint ();
567 nsock = mono_poll (pfds, maxfd, -1);
568 } while (nsock == -1 && errno == EINTR);
571 * Apart from EINTR, we only check EBADF, for the rest:
572 * EINVAL: mono_poll() 'protects' us from descriptor
573 * numbers above the limit if using select() by marking
574 * then as MONO_POLLERR. If a system poll() is being
575 * used, the number of descriptor we're passing will not
576 * be over sysconf(_SC_OPEN_MAX), as the error would have
577 * happened when opening.
579 * EFAULT: we own the memory pointed by pfds.
580 * ENOMEM: we're doomed anyway
584 if (nsock == -1 && errno == EBADF) {
585 pfds->revents = 0; /* Just in case... */
586 nsock = mark_bad_fds (pfds, maxfd);
589 if ((pfds->revents & POLL_ERRORS) != 0) {
590 /* We're supposed to die now, as the pipe has been closed */
592 socket_io_cleanup (data);
596 /* Got a new socket */
597 if ((pfds->revents & MONO_POLLIN) != 0) {
600 for (i = 1; i < allocated; i++) {
602 if (pfd->fd == -1 || data->newpfd == NULL ||
603 pfd->fd == data->newpfd->fd)
607 if (i == allocated) {
612 allocated = allocated * 2;
613 pfds = g_renew (mono_pollfd, oldfd, allocated);
615 for (; i < allocated; i++)
616 INIT_POLLFD (&pfds [i], -1, 0);
619 nread = read (data->pipe [0], one, 1);
621 nread = recv ((SOCKET) data->pipe [0], one, 1, 0);
625 return; /* we're closed */
628 INIT_POLLFD (&pfds [i], data->newpfd->fd, data->newpfd->events);
629 ReleaseSemaphore (data->new_sem, 1, NULL);
638 EnterCriticalSection (&data->io_lock);
639 if (data->inited == 3) {
641 LeaveCriticalSection (&data->io_lock);
642 return; /* cleanup called */
645 for (i = 1; i < maxfd && nsock > 0; i++) {
647 if (pfd->fd == -1 || pfd->revents == 0)
651 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
652 if (list != NULL && (pfd->revents & (MONO_POLLIN | POLL_ERRORS)) != 0) {
653 list = process_io_event (list, MONO_POLLIN);
656 if (list != NULL && (pfd->revents & (MONO_POLLOUT | POLL_ERRORS)) != 0) {
657 list = process_io_event (list, MONO_POLLOUT);
661 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (pfd->fd), list);
662 pfd->events = get_events_from_list (list);
664 mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
670 LeaveCriticalSection (&data->io_lock);
675 #define EPOLL_ERRORS (EPOLLERR | EPOLLHUP)
676 #define EPOLL_NEVENTS 128
678 socket_io_epoll_main (gpointer p)
682 MonoInternalThread *thread;
683 struct epoll_event *events, *evt;
685 gpointer async_results [EPOLL_NEVENTS * 2]; // * 2 because each loop can add up to 2 results here
689 epollfd = data->epollfd;
690 thread = mono_thread_internal_current ();
691 events = g_new0 (struct epoll_event, EPOLL_NEVENTS);
696 if (THREAD_WANTS_A_BREAK (thread))
697 mono_thread_interruption_checkpoint ();
699 EPOLL_DEBUG ("epoll_wait init");
700 ready = epoll_wait (epollfd, events, EPOLL_NEVENTS, -1);
703 EPOLL_DEBUG ("epoll_wait end with %d ready sockets (%d %s).", ready, err, (ready == -1) ? g_strerror (err) : "");
706 } while (ready == -1 && errno == EINTR);
712 g_warning ("epoll_wait: %d %s", err, g_strerror (err));
718 EnterCriticalSection (&data->io_lock);
719 if (data->inited == 3) {
722 LeaveCriticalSection (&data->io_lock);
723 return; /* cleanup called */
727 for (i = 0; i < ready; i++) {
734 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
735 EPOLL_DEBUG ("Event %d on %d list length: %d", evt->events, fd, mono_mlist_length (list));
736 if (list != NULL && (evt->events & (EPOLLIN | EPOLL_ERRORS)) != 0) {
737 ares = get_io_event (&list, MONO_POLLIN);
739 async_results [nresults++] = ares;
742 if (list != NULL && (evt->events & (EPOLLOUT | EPOLL_ERRORS)) != 0) {
743 ares = get_io_event (&list, MONO_POLLOUT);
745 async_results [nresults++] = ares;
749 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (fd), list);
750 evt->events = get_events_from_list (list);
751 EPOLL_DEBUG ("MOD %d to %d", fd, evt->events);
752 if (epoll_ctl (epollfd, EPOLL_CTL_MOD, fd, evt)) {
753 if (epoll_ctl (epollfd, EPOLL_CTL_ADD, fd, evt) == -1) {
756 EPOLL_DEBUG ("epoll_ctl(MOD): %d %s fd: %d events: %d", err, g_strerror (err), fd, evt->events);
762 mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (fd));
763 EPOLL_DEBUG ("DEL %d", fd);
764 epoll_ctl (epollfd, EPOLL_CTL_DEL, fd, evt);
767 LeaveCriticalSection (&data->io_lock);
768 threadpool_append_jobs (&async_io_tp, (MonoObject **) async_results, nresults);
769 memset (async_results, 0, sizeof (gpointer) * nresults);
776 * select/poll wake up when a socket is closed, but epoll just removes
777 * the socket from its internal list without notification.
780 mono_thread_pool_remove_socket (int sock)
782 MonoMList *list, *next;
783 MonoSocketAsyncResult *state;
785 if (socket_io_data.inited == 0)
788 EnterCriticalSection (&socket_io_data.io_lock);
789 if (socket_io_data.sock_to_state == NULL) {
790 LeaveCriticalSection (&socket_io_data.io_lock);
793 list = mono_g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
795 mono_g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
796 LeaveCriticalSection (&socket_io_data.io_lock);
799 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
800 if (state->operation == AIO_OP_RECEIVE)
801 state->operation = AIO_OP_RECV_JUST_CALLBACK;
802 else if (state->operation == AIO_OP_SEND)
803 state->operation = AIO_OP_SEND_JUST_CALLBACK;
805 next = mono_mlist_remove_item (list, list);
806 list = process_io_event (list, MONO_POLLIN);
808 process_io_event (list, MONO_POLLOUT);
816 connect_hack (gpointer x)
818 struct sockaddr_in *addr = (struct sockaddr_in *) x;
821 while (connect ((SOCKET) socket_io_data.pipe [1], (SOCKADDR *) addr, sizeof (struct sockaddr_in))) {
824 g_warning ("Error initializing async. sockets %d.", WSAGetLastError ());
825 g_assert (WSAGetLastError ());
832 socket_io_init (SocketIOData *data)
835 struct sockaddr_in server;
836 struct sockaddr_in client;
843 if (data->inited >= 2) // 2 -> initialized, 3-> cleaned up
846 inited = InterlockedCompareExchange (&data->inited, 1, 0);
849 if (data->inited >= 2)
855 EnterCriticalSection (&data->io_lock);
858 data->epoll_disabled = (g_getenv ("MONO_DISABLE_AIO") != NULL);
859 if (FALSE == data->epoll_disabled) {
860 data->epollfd = epoll_create (256);
861 data->epoll_disabled = (data->epollfd == -1);
862 if (data->epoll_disabled && g_getenv ("MONO_DEBUG"))
863 g_message ("epoll_create() failed. Using plain poll().");
868 data->epoll_disabled = TRUE;
872 if (data->epoll_disabled) {
873 if (pipe (data->pipe) != 0) {
883 srv = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
884 g_assert (srv != INVALID_SOCKET);
885 data->pipe [1] = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
886 g_assert (data->pipe [1] != INVALID_SOCKET);
888 server.sin_family = AF_INET;
889 server.sin_addr.s_addr = inet_addr ("127.0.0.1");
891 if (bind (srv, (SOCKADDR *) &server, sizeof (server))) {
892 g_print ("%d\n", WSAGetLastError ());
896 len = sizeof (server);
897 getsockname (srv, (SOCKADDR *) &server, &len);
899 mono_thread_create (mono_get_root_domain (), connect_hack, &server);
900 len = sizeof (server);
901 data->pipe [0] = accept (srv, (SOCKADDR *) &client, &len);
902 g_assert (data->pipe [0] != INVALID_SOCKET);
905 data->sock_to_state = mono_g_hash_table_new_type (g_direct_hash, g_direct_equal, MONO_HASH_VALUE_GC);
907 if (data->epoll_disabled) {
908 data->new_sem = CreateSemaphore (NULL, 1, 1, NULL);
909 g_assert (data->new_sem != NULL);
912 stack_size = mono_threads_get_default_stacksize ();
913 /* 128k stacks could lead to problems on 64 bit systems with large pagesizes+altstack */
914 mono_threads_set_default_stacksize (128 * (sizeof (gpointer) / 4) * 1024);
915 if (data->epoll_disabled) {
916 mono_thread_create_internal (mono_get_root_domain (), socket_io_poll_main, data, TRUE);
920 mono_thread_create_internal (mono_get_root_domain (), socket_io_epoll_main, data, TRUE);
923 mono_threads_set_default_stacksize (stack_size);
924 LeaveCriticalSection (&data->io_lock);
929 socket_io_add_poll (MonoSocketAsyncResult *state)
934 SocketIOData *data = &socket_io_data;
937 if (mono_runtime_is_shutting_down () || data->inited == 3 || data->sock_to_state == NULL)
940 #if defined(PLATFORM_MACOSX) || defined(PLATFORM_BSD) || defined(HOST_WIN32) || defined(PLATFORM_SOLARIS)
941 /* select() for connect() does not work well on the Mac. Bug #75436. */
942 /* Bug #77637 for the BSD 6 case */
943 /* Bug #78888 for the Windows case */
944 if (state->operation == AIO_OP_CONNECT && state->blocking == TRUE) {
945 //FIXME: increment number of threads while this one is waiting?
946 threadpool_append_job (&async_io_tp, (MonoObject *) state);
950 WaitForSingleObject (data->new_sem, INFINITE);
951 if (data->newpfd == NULL)
952 data->newpfd = g_new0 (mono_pollfd, 1);
954 EnterCriticalSection (&data->io_lock);
955 if (data->sock_to_state == NULL) {
956 LeaveCriticalSection (&data->io_lock);
960 /* FIXME: 64 bit issue: handle can be a pointer on windows? */
961 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (state->handle));
963 list = mono_mlist_alloc ((MonoObject*)state);
965 list = mono_mlist_append (list, (MonoObject*)state);
968 events = get_events_from_list (list);
969 INIT_POLLFD (data->newpfd, GPOINTER_TO_INT (state->handle), events);
970 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (state->handle), list);
971 LeaveCriticalSection (&data->io_lock);
972 *msg = (char) state->operation;
974 w = write (data->pipe [1], msg, 1);
977 send ((SOCKET) data->pipe [1], msg, 1, 0);
983 socket_io_add_epoll (MonoSocketAsyncResult *state)
986 SocketIOData *data = &socket_io_data;
987 struct epoll_event event;
991 if (mono_runtime_is_shutting_down () || data->inited == 3 || data->sock_to_state == NULL)
994 memset (&event, 0, sizeof (struct epoll_event));
995 fd = GPOINTER_TO_INT (state->handle);
996 EnterCriticalSection (&data->io_lock);
997 if (data->sock_to_state == NULL) {
998 LeaveCriticalSection (&data->io_lock);
1001 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
1003 list = mono_mlist_alloc ((MonoObject*)state);
1004 epoll_op = EPOLL_CTL_ADD;
1006 list = mono_mlist_append (list, (MonoObject*)state);
1007 epoll_op = EPOLL_CTL_MOD;
1010 ievt = get_events_from_list (list);
1011 if ((ievt & MONO_POLLIN) != 0)
1012 event.events |= EPOLLIN;
1013 if ((ievt & MONO_POLLOUT) != 0)
1014 event.events |= EPOLLOUT;
1016 mono_g_hash_table_replace (data->sock_to_state, state->handle, list);
1018 EPOLL_DEBUG ("%s %d with %d", epoll_op == EPOLL_CTL_ADD ? "ADD" : "MOD", fd, event.events);
1019 if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
1021 if (epoll_op == EPOLL_CTL_ADD && err == EEXIST) {
1022 epoll_op = EPOLL_CTL_MOD;
1023 if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
1024 g_message ("epoll_ctl(MOD): %d %s", err, g_strerror (err));
1028 LeaveCriticalSection (&data->io_lock);
1035 socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
1037 if (async_tp.pool_status == 2 || mono_runtime_is_shutting_down ())
1040 socket_io_init (&socket_io_data);
1042 MONO_OBJECT_SETREF (state, ares, ares);
1044 if (socket_io_data.epoll_disabled == FALSE) {
1045 if (socket_io_add_epoll (state))
1049 socket_io_add_poll (state);
1052 #ifndef DISABLE_SOCKETS
1054 socket_io_filter (MonoObject *target, MonoObject *state)
1057 MonoSocketAsyncResult *sock_res;
1060 if (target == NULL || state == NULL)
1063 klass = target->vtable->klass;
1064 if (socket_async_call_klass == NULL && is_socketasynccall (klass))
1065 socket_async_call_klass = klass;
1067 if (process_async_call_klass == NULL && is_sdp_asyncreadhandler (klass))
1068 process_async_call_klass = klass;
1070 if (klass != socket_async_call_klass && klass != process_async_call_klass)
1073 sock_res = (MonoSocketAsyncResult *) state;
1074 op = sock_res->operation;
1075 if (op < AIO_OP_FIRST || op >= AIO_OP_LAST)
1080 #endif /* !DISABLE_SOCKETS */
1082 /* Returns the exception thrown when invoking, if any */
1084 mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares)
1086 ASyncCall *ac = (ASyncCall *)ares->object_data;
1087 MonoObject *res, *exc = NULL;
1088 MonoArray *out_args = NULL;
1089 HANDLE wait_event = NULL;
1091 if (ares->execution_context) {
1092 /* use captured ExecutionContext (if available) */
1093 MONO_OBJECT_SETREF (ares, original_context, mono_thread_get_execution_context ());
1094 mono_thread_set_execution_context (ares->execution_context);
1096 ares->original_context = NULL;
1100 /* Fast path from ThreadPool.*QueueUserWorkItem */
1101 void *pa = ares->async_state;
1102 mono_runtime_delegate_invoke (ares->async_delegate, &pa, &exc);
1104 MonoObject *cb_exc = NULL;
1106 ac->msg->exc = NULL;
1107 res = mono_message_invoke (ares->async_delegate, ac->msg, &exc, &out_args);
1108 MONO_OBJECT_SETREF (ac, res, res);
1109 MONO_OBJECT_SETREF (ac, msg->exc, exc);
1110 MONO_OBJECT_SETREF (ac, out_args, out_args);
1112 mono_monitor_enter ((MonoObject *) ares);
1113 ares->completed = 1;
1114 if (ares->handle != NULL)
1115 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
1116 mono_monitor_exit ((MonoObject *) ares);
1117 /* notify listeners */
1118 if (wait_event != NULL)
1119 SetEvent (wait_event);
1121 /* call async callback if cb_method != null*/
1122 if (ac != NULL && ac->cb_method) {
1125 mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &cb_exc);
1126 MONO_OBJECT_SETREF (ac->msg, exc, cb_exc);
1133 /* restore original thread execution context if flow isn't suppressed, i.e. non null */
1134 if (ares->original_context) {
1135 mono_thread_set_execution_context (ares->original_context);
1136 ares->original_context = NULL;
1142 threadpool_start_idle_threads (ThreadPool *tp)
1146 if (tp->pool_status == 1 && !tp->is_io)
1147 mono_thread_create_internal (mono_get_root_domain (), monitor_thread, tp, TRUE);
1151 if (n >= tp->min_threads)
1153 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n)
1156 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
1157 mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE);
1158 SleepEx (100, TRUE);
1163 threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer))
1165 memset (tp, 0, sizeof (ThreadPool));
1166 MONO_SEM_INIT (&tp->lock, 1);
1167 tp->min_threads = min_threads;
1168 tp->max_threads = max_threads;
1169 tp->async_invoke = async_invoke;
1170 MONO_SEM_INIT (&tp->new_job, 0);
1174 init_perf_counter (const char *category, const char *counter)
1176 MonoString *category_str;
1177 MonoString *counter_str;
1178 MonoString *machine;
1183 if (category == NULL || counter == NULL)
1185 root = mono_get_root_domain ();
1186 category_str = mono_string_new (root, category);
1187 counter_str = mono_string_new (root, counter);
1188 machine = mono_string_new (root, ".");
1189 return mono_perfcounter_get_impl (category_str, counter_str, NULL, machine, &type, &custom);
1194 print_pool_info (ThreadPool *tp)
1197 // if (tp->tail - tp->head == 0)
1200 g_print ("Pool status? %d\n", InterlockedCompareExchange (&tp->pool_status, 0, 0));
1201 g_print ("Min. threads: %d\n", InterlockedCompareExchange (&tp->min_threads, 0, 0));
1202 g_print ("Max. threads: %d\n", InterlockedCompareExchange (&tp->max_threads, 0, 0));
1203 g_print ("nthreads: %d\n", InterlockedCompareExchange (&tp->nthreads, 0, 0));
1204 g_print ("busy threads: %d\n", InterlockedCompareExchange (&tp->busy_threads, 0, 0));
1205 g_print ("Waiting: %d\n", InterlockedCompareExchange (&tp->waiting, 0, 0));
1206 g_print ("Queued: %d\n", (tp->tail - tp->head));
1207 if (tp == &async_tp) {
1209 EnterCriticalSection (&wsqs_lock);
1210 for (i = 0; i < wsqs->len; i++) {
1211 g_print ("\tWSQ %d: %d\n", i, mono_wsq_count (g_ptr_array_index (wsqs, i)));
1213 LeaveCriticalSection (&wsqs_lock);
1215 g_print ("\tSockets: %d\n", mono_g_hash_table_size (socket_io_data.sock_to_state));
1217 g_print ("-------------\n");
1221 signal_handler (int signo)
1226 MONO_SEM_WAIT (&tp->lock);
1227 g_print ("\n-----Non-IO-----\n");
1228 print_pool_info (tp);
1229 MONO_SEM_POST (&tp->lock);
1231 MONO_SEM_WAIT (&tp->lock);
1232 g_print ("\n-----IO-----\n");
1233 print_pool_info (tp);
1234 MONO_SEM_POST (&tp->lock);
1240 monitor_thread (gpointer data)
1243 MonoInternalThread *thread;
1249 thread = mono_thread_internal_current ();
1254 ts = mono_msec_ticks ();
1255 if (SleepEx (ms, TRUE) == 0)
1257 ms -= (mono_msec_ticks () - ts);
1258 if (mono_runtime_is_shutting_down ())
1260 if (THREAD_WANTS_A_BREAK (thread))
1261 mono_thread_interruption_checkpoint ();
1264 if (mono_runtime_is_shutting_down ())
1266 if (tp->waiting > 0)
1268 MONO_SEM_WAIT (&tp->lock);
1269 need_one = (tp->head != tp->tail);
1271 EnterCriticalSection (&wsqs_lock);
1272 for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
1274 wsq = g_ptr_array_index (wsqs, i);
1275 if (mono_wsq_count (wsq) > 0) {
1280 LeaveCriticalSection (&wsqs_lock);
1282 MONO_SEM_POST (&tp->lock);
1284 threadpool_start_thread (tp);
1289 mono_thread_pool_init ()
1291 gint threads_per_cpu = 1;
1293 gint cpu_count = mono_cpu_count ();
1299 result = InterlockedCompareExchange (&tp_inited, 1, 0);
1308 MONO_GC_REGISTER_ROOT_SINGLE (async_tp.first);
1309 MONO_GC_REGISTER_ROOT_SINGLE (async_tp.last);
1310 MONO_GC_REGISTER_ROOT_SINGLE (async_tp.unused);
1311 MONO_GC_REGISTER_ROOT_SINGLE (async_io_tp.first);
1312 MONO_GC_REGISTER_ROOT_SINGLE (async_io_tp.unused);
1313 MONO_GC_REGISTER_ROOT_SINGLE (async_io_tp.last);
1315 MONO_GC_REGISTER_ROOT_FIXED (socket_io_data.sock_to_state);
1316 InitializeCriticalSection (&socket_io_data.io_lock);
1317 if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
1318 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
1319 if (threads_per_cpu < 1)
1320 threads_per_cpu = 1;
1323 thread_count = MIN (cpu_count * threads_per_cpu, 100 * cpu_count);
1324 threadpool_init (&async_tp, thread_count, MAX (100 * cpu_count, thread_count), async_invoke_thread);
1325 threadpool_init (&async_io_tp, cpu_count * 2, cpu_count * 4, async_invoke_thread);
1326 async_io_tp.is_io = TRUE;
1328 async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
1329 g_assert (async_call_klass);
1331 InitializeCriticalSection (&wsqs_lock);
1332 wsqs = g_ptr_array_sized_new (MAX (100 * cpu_count, thread_count));
1335 async_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "Work Items Added");
1336 g_assert (async_tp.pc_nitems);
1338 async_io_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "IO Work Items Added");
1339 g_assert (async_io_tp.pc_nitems);
1341 async_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of Threads");
1342 g_assert (async_tp.pc_nthreads);
1344 async_io_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of IO Threads");
1345 g_assert (async_io_tp.pc_nthreads);
1348 signal (SIGALRM, signal_handler);
1353 static MonoAsyncResult *
1354 create_simple_asyncresult (MonoObject *target, MonoObject *state)
1356 MonoDomain *domain = mono_domain_get ();
1357 MonoAsyncResult *ares;
1359 /* Don't call mono_async_result_new() to avoid capturing the context */
1360 ares = (MonoAsyncResult *) mono_object_new (domain, mono_defaults.asyncresult_class);
1361 MONO_OBJECT_SETREF (ares, async_delegate, target);
1362 MONO_OBJECT_SETREF (ares, async_state, state);
1367 icall_append_io_job (MonoObject *target, MonoSocketAsyncResult *state)
1369 MonoAsyncResult *ares;
1371 ares = create_simple_asyncresult (target, (MonoObject *) state);
1372 socket_io_add (ares, state);
1376 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
1379 MonoDomain *domain = mono_domain_get ();
1380 MonoAsyncResult *ares;
1383 ac = (ASyncCall*)mono_object_new (domain, async_call_klass);
1384 MONO_OBJECT_SETREF (ac, msg, msg);
1385 MONO_OBJECT_SETREF (ac, state, state);
1387 if (async_callback) {
1388 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
1389 MONO_OBJECT_SETREF (ac, cb_target, async_callback);
1392 ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
1393 MONO_OBJECT_SETREF (ares, async_delegate, target);
1395 #ifndef DISABLE_SOCKETS
1396 if (socket_io_filter (target, state)) {
1397 socket_io_add (ares, (MonoSocketAsyncResult *) state);
1401 threadpool_append_job (&async_tp, (MonoObject *) ares);
1406 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1414 /* check if already finished */
1415 mono_monitor_enter ((MonoObject *) ares);
1417 if (ares->endinvoke_called) {
1418 *exc = (MonoObject *) mono_get_exception_invalid_operation (NULL);
1419 mono_monitor_exit ((MonoObject *) ares);
1423 ares->endinvoke_called = 1;
1424 /* wait until we are really finished */
1425 if (!ares->completed) {
1426 if (ares->handle == NULL) {
1427 wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1428 g_assert(wait_event != 0);
1429 MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), wait_event));
1431 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
1433 mono_monitor_exit ((MonoObject *) ares);
1434 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
1436 mono_monitor_exit ((MonoObject *) ares);
1439 ac = (ASyncCall *) ares->object_data;
1440 g_assert (ac != NULL);
1441 *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1442 *out_args = ac->out_args;
1448 threadpool_kill_idle_threads (ThreadPool *tp)
1452 n = (gint) InterlockedCompareExchange (&tp->max_threads, 0, -1);
1455 MONO_SEM_POST (&tp->new_job);
1460 mono_thread_pool_cleanup (void)
1462 if (!(async_tp.pool_status == 0 || async_tp.pool_status == 2)) {
1463 if (!(async_tp.pool_status == 1 && InterlockedCompareExchange (&async_tp.pool_status, 2, 1) == 2)) {
1464 InterlockedExchange (&async_io_tp.pool_status, 2);
1465 MONO_SEM_WAIT (&async_tp.lock);
1466 threadpool_free_queue (&async_tp);
1467 threadpool_kill_idle_threads (&async_tp);
1468 MONO_SEM_POST (&async_tp.lock);
1470 socket_io_cleanup (&socket_io_data); /* Empty when DISABLE_SOCKETS is defined */
1471 MONO_SEM_WAIT (&async_io_tp.lock);
1472 threadpool_free_queue (&async_io_tp);
1473 threadpool_kill_idle_threads (&async_io_tp);
1474 MONO_SEM_POST (&async_io_tp.lock);
1475 MONO_SEM_DESTROY (&async_io_tp.new_job);
1479 EnterCriticalSection (&wsqs_lock);
1480 mono_wsq_cleanup ();
1482 g_ptr_array_free (wsqs, TRUE);
1484 LeaveCriticalSection (&wsqs_lock);
1485 MONO_SEM_DESTROY (&async_tp.new_job);
1488 /* Caller must enter &tp->lock */
1490 dequeue_job_nolock (ThreadPool *tp)
1498 if (mono_runtime_is_shutting_down ())
1500 if (!list || tp->head == tp->tail)
1503 array = (MonoArray *) mono_mlist_get_data (list);
1504 ar = mono_array_get (array, MonoObject *, tp->head % QUEUE_LENGTH);
1505 mono_array_set (array, MonoObject *, tp->head % QUEUE_LENGTH, NULL);
1507 if ((tp->head % QUEUE_LENGTH) == 0) {
1509 tp->first = mono_mlist_next (list);
1510 if (tp->first == NULL)
1512 if (mono_mlist_length (tp->unused) < 20) {
1513 /* reuse this chunk */
1514 tp->unused = mono_mlist_set_next (list, tp->unused);
1516 tp->head -= QUEUE_LENGTH;
1517 tp->tail -= QUEUE_LENGTH;
1520 } while (ar == NULL);
1525 threadpool_start_thread (ThreadPool *tp)
1529 while (!mono_runtime_is_shutting_down () && (n = tp->nthreads) < tp->max_threads) {
1530 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n) {
1531 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
1532 mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE);
1541 pulse_on_new_job (ThreadPool *tp)
1544 MONO_SEM_POST (&tp->new_job);
1548 icall_append_job (MonoObject *ar)
1550 threadpool_append_job (&async_tp, ar);
1554 threadpool_append_job (ThreadPool *tp, MonoObject *ar)
1556 threadpool_append_jobs (tp, &ar, 1);
1560 create_or_reuse_list (ThreadPool *tp)
1568 tp->unused = mono_mlist_next (list);
1569 mono_mlist_set_next (list, NULL);
1570 //TP_DEBUG (tp->nodes_reused++);
1572 array = mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, QUEUE_LENGTH);
1573 list = mono_mlist_alloc ((MonoObject *) array);
1574 //TP_DEBUG (tp->nodes_created++);
1580 threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs)
1582 static int job_counter;
1587 gboolean lock_taken = FALSE; /* We won't take the lock when the local queue is used */
1589 if (mono_runtime_is_shutting_down ())
1592 if (tp->pool_status == 0 && InterlockedCompareExchange (&tp->pool_status, 1, 0) == 0)
1593 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, tp, TRUE);
1595 for (i = 0; i < njobs; i++) {
1597 if (ar == NULL || mono_domain_is_unloading (ar->vtable->domain))
1598 continue; /* Might happen when cleaning domain jobs */
1599 if (!tp->is_io && (InterlockedIncrement (&job_counter) % 10) == 0) {
1600 MonoAsyncResult *o = (MonoAsyncResult *) ar;
1601 o->add_time = mono_100ns_ticks ();
1603 threadpool_jobs_inc (ar);
1604 mono_perfcounter_update_value (tp->pc_nitems, TRUE, 1);
1605 if (!tp->is_io && mono_wsq_local_push (ar))
1609 MONO_SEM_WAIT (&tp->lock);
1612 if ((tp->tail % QUEUE_LENGTH) == 0) {
1613 list = create_or_reuse_list (tp);
1614 if (tp->last != NULL)
1615 mono_mlist_set_next (tp->last, list);
1617 if (tp->first == NULL)
1618 tp->first = tp->last;
1621 array = (MonoArray *) mono_mlist_get_data (tp->last);
1622 mono_array_setref (array, tp->tail % QUEUE_LENGTH, ar);
1626 MONO_SEM_POST (&tp->lock);
1628 for (i = 0; i < MIN(njobs, tp->max_threads); i++)
1629 pulse_on_new_job (tp);
1633 threadpool_clear_queue (ThreadPool *tp, MonoDomain *domain)
1642 MONO_SEM_WAIT (&tp->lock);
1643 current = tp->first;
1645 array = (MonoArray *) mono_mlist_get_data (current);
1646 for (i = 0; i < QUEUE_LENGTH; i++) {
1647 obj = mono_array_get (array, MonoObject*, i);
1648 if (obj != NULL && obj->vtable->domain == domain) {
1650 mono_array_setref (array, i, NULL);
1651 threadpool_jobs_dec (obj);
1654 current = mono_mlist_next (current);
1657 if (!domain_count) {
1658 MONO_SEM_POST (&tp->lock);
1662 current = tp->first;
1667 MONO_SEM_POST (&tp->lock);
1668 /* Re-add everything but the nullified elements */
1670 array = (MonoArray *) mono_mlist_get_data (current);
1671 threadpool_append_jobs (tp, mono_array_addr (array, MonoObject *, 0), QUEUE_LENGTH);
1672 memset (mono_array_addr (array, MonoObject *, 0), 0, sizeof (MonoObject *) * QUEUE_LENGTH);
1673 current = mono_mlist_next (current);
1678 * Clean up the threadpool of all domain jobs.
1679 * Can only be called as part of the domain unloading process as
1680 * it will wait for all jobs to be visible to the interruption code.
1683 mono_thread_pool_remove_domain_jobs (MonoDomain *domain, int timeout)
1687 guint32 start_time = 0;
1689 g_assert (domain->state == MONO_APPDOMAIN_UNLOADING);
1691 threadpool_clear_queue (&async_tp, domain);
1692 threadpool_clear_queue (&async_io_tp, domain);
1695 * There might be some threads out that could be about to execute stuff from the given domain.
1696 * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
1698 sem_handle = CreateSemaphore (NULL, 0, 1, NULL);
1700 domain->cleanup_semaphore = sem_handle;
1702 * The memory barrier here is required to have global ordering between assigning to cleanup_semaphone
1703 * and reading threadpool_jobs.
1704 * Otherwise this thread could read a stale version of threadpool_jobs and wait forever.
1706 mono_memory_write_barrier ();
1708 if (domain->threadpool_jobs && timeout != -1)
1709 start_time = mono_msec_ticks ();
1710 while (domain->threadpool_jobs) {
1711 WaitForSingleObject (sem_handle, timeout);
1712 if (timeout != -1 && (mono_msec_ticks () - start_time) > timeout) {
1718 domain->cleanup_semaphore = NULL;
1719 CloseHandle (sem_handle);
1724 threadpool_free_queue (ThreadPool *tp)
1726 tp->head = tp->tail = 0;
1732 mono_thread_pool_is_queue_array (MonoArray *o)
1736 // FIXME: need some fix in sgen code.
1737 // There are roots at: async*tp.unused (MonoMList) and wsqs [n]->queue (MonoArray)
1738 return obj == async_tp.first || obj == async_io_tp.first;
1747 EnterCriticalSection (&wsqs_lock);
1748 wsq = mono_wsq_create ();
1750 LeaveCriticalSection (&wsqs_lock);
1753 for (i = 0; i < wsqs->len; i++) {
1754 if (g_ptr_array_index (wsqs, i) == NULL) {
1755 wsqs->pdata [i] = wsq;
1756 LeaveCriticalSection (&wsqs_lock);
1760 g_ptr_array_add (wsqs, wsq);
1761 LeaveCriticalSection (&wsqs_lock);
1766 remove_wsq (MonoWSQ *wsq)
1773 EnterCriticalSection (&wsqs_lock);
1775 LeaveCriticalSection (&wsqs_lock);
1778 g_ptr_array_remove_fast (wsqs, wsq);
1780 while (mono_wsq_local_pop (&data)) {
1781 threadpool_jobs_dec (data);
1784 mono_wsq_destroy (wsq);
1785 LeaveCriticalSection (&wsqs_lock);
1789 try_steal (gpointer *data, gboolean retry)
1794 if (wsqs == NULL || data == NULL || *data != NULL)
1799 if (mono_runtime_is_shutting_down ())
1801 for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
1802 if (mono_runtime_is_shutting_down ()) {
1805 mono_wsq_try_steal (wsqs->pdata [i], data, ms);
1806 if (*data != NULL) {
1811 } while (retry && ms < 11);
1815 dequeue_or_steal (ThreadPool *tp, gpointer *data)
1817 if (mono_runtime_is_shutting_down ())
1819 TP_DEBUG ("Dequeue");
1820 MONO_SEM_WAIT (&tp->lock);
1821 *data = dequeue_job_nolock (tp);
1822 MONO_SEM_POST (&tp->lock);
1823 if (!tp->is_io && !*data)
1824 try_steal (data, FALSE);
1825 return (*data != NULL);
1829 process_idle_times (ThreadPool *tp, gint64 t)
1833 gboolean compute_avg;
1837 if (tp->ignore_times || t <= 0)
1840 compute_avg = FALSE;
1841 ticks = mono_100ns_ticks ();
1843 SPIN_LOCK (tp->sp_lock);
1844 if (tp->ignore_times) {
1845 SPIN_UNLOCK (tp->sp_lock);
1850 if (tp->last_check == 0)
1851 tp->last_check = ticks;
1852 else if (tp->last_check > 0 && (ticks - tp->last_check) > 5000000) {
1853 tp->ignore_times = 1;
1856 SPIN_UNLOCK (tp->sp_lock);
1861 //printf ("Items: %d Time elapsed: %.3fs\n", tp->n_sum, (ticks - tp->last_check) / 10000.0);
1862 tp->last_check = ticks;
1864 avg = tp->time_sum / tp->n_sum;
1865 if (tp->averages [1] == 0) {
1866 tp->averages [1] = avg;
1868 per1 = ((100 * (ABS (avg - tp->averages [1]))) / tp->averages [1]);
1870 if (avg > tp->averages [1]) {
1871 if (tp->averages [1] < tp->averages [0]) {
1876 } else if (avg < tp->averages [1] && tp->averages [1] < tp->averages [0]) {
1881 min = tp->min_threads;
1883 if ((n - min) < min && tp->busy_threads == n)
1887 if (new_threads != 0) {
1888 printf ("n: %d per1: %lld avg=%lld avg1=%lld avg0=%lld\n", new_threads, per1, avg, tp->averages [1], tp->averages [0]);
1896 tp->averages [0] = tp->averages [1];
1897 tp->averages [1] = avg;
1898 tp->ignore_times = 0;
1900 if (new_threads == -1) {
1901 if (tp->destroy_thread == 0 && InterlockedCompareExchange (&tp->destroy_thread, 1, 0) == 0)
1902 pulse_on_new_job (tp);
1907 should_i_die (ThreadPool *tp)
1909 gboolean result = FALSE;
1910 if (tp->destroy_thread == 1 && InterlockedCompareExchange (&tp->destroy_thread, 0, 1) == 1)
1911 result = (tp->nthreads > tp->min_threads);
1916 async_invoke_thread (gpointer data)
1919 MonoInternalThread *thread;
1929 thread = mono_thread_internal_current ();
1931 tp_start_func (tp_hooks_user_data);
1934 MonoAsyncResult *ar;
1936 gboolean is_io_task;
1941 ar = (MonoAsyncResult *) data;
1943 InterlockedIncrement (&tp->busy_threads);
1944 #ifndef DISABLE_SOCKET
1945 klass = ((MonoObject *) data)->vtable->klass;
1946 is_io_task = !is_corlib_asyncresult (klass);
1949 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1950 is_socket = is_socketasyncresult (klass);
1952 switch (state->operation) {
1953 case AIO_OP_RECEIVE:
1954 state->total = ICALL_RECV (state);
1957 state->total = ICALL_SEND (state);
1962 /* worker threads invokes methods in different domains,
1963 * so we need to set the right domain here */
1964 domain = ((MonoObject *)ar)->vtable->domain;
1967 if (mono_domain_is_unloading (domain) || mono_runtime_is_shutting_down ()) {
1968 threadpool_jobs_dec ((MonoObject *)ar);
1971 InterlockedDecrement (&tp->busy_threads);
1973 mono_thread_push_appdomain_ref (domain);
1974 if (threadpool_jobs_dec ((MonoObject *)ar)) {
1977 mono_thread_pop_appdomain_ref ();
1978 InterlockedDecrement (&tp->busy_threads);
1982 if (mono_domain_set (domain, FALSE)) {
1985 if (tp_item_begin_func)
1986 tp_item_begin_func (tp_item_user_data);
1988 if (!is_io_task && ar->add_time > 0)
1989 process_idle_times (tp, ar->add_time);
1990 exc = mono_async_invoke (tp, ar);
1991 if (tp_item_end_func)
1992 tp_item_end_func (tp_item_user_data);
1993 if (exc && mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_CURRENT) {
1997 klass = exc->vtable->klass;
1998 unloaded = is_appdomainunloaded_exception (klass);
1999 if (!unloaded && klass != mono_defaults.threadabortexception_class) {
2000 mono_unhandled_exception (exc);
2004 if (is_socket && tp->is_io) {
2005 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
2007 if (state->completed && state->callback) {
2008 MonoAsyncResult *cb_ares;
2009 cb_ares = create_simple_asyncresult ((MonoObject *) state->callback,
2010 (MonoObject *) state);
2011 icall_append_job ((MonoObject *) cb_ares);
2014 mono_domain_set (mono_get_root_domain (), TRUE);
2016 mono_thread_pop_appdomain_ref ();
2017 InterlockedDecrement (&tp->busy_threads);
2018 /* If the callee changes the background status, set it back to TRUE */
2019 if (!mono_thread_test_state (thread , ThreadState_Background))
2020 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
2026 must_die = should_i_die (tp);
2027 TP_DEBUG ("Trying to get a job");
2028 if (!must_die && (tp->is_io || !mono_wsq_local_pop (&data)))
2029 dequeue_or_steal (tp, &data);
2030 TP_DEBUG ("Done trying to get a job %p", data);
2033 while (!must_die && !data && n_naps < 4) {
2036 TP_DEBUG ("Waiting");
2037 InterlockedIncrement (&tp->waiting);
2038 #if defined(__OpenBSD__)
2039 while ((res = mono_sem_wait (&tp->new_job, TRUE)) == -1) {// && errno == EINTR) {
2041 while ((res = mono_sem_timedwait (&tp->new_job, 2000, TRUE)) == -1) {// && errno == EINTR) {
2043 if (mono_runtime_is_shutting_down ())
2045 if (THREAD_WANTS_A_BREAK (thread))
2046 mono_thread_interruption_checkpoint ();
2048 TP_DEBUG ("Done waiting");
2049 InterlockedDecrement (&tp->waiting);
2050 if (mono_runtime_is_shutting_down ())
2052 must_die = should_i_die (tp);
2053 dequeue_or_steal (tp, &data);
2057 if (!data && tp->is_io && !mono_runtime_is_shutting_down ()) {
2058 mono_wsq_local_pop (&data);
2059 if (data && must_die) {
2060 InterlockedCompareExchange (&tp->destroy_thread, 1, 0);
2061 pulse_on_new_job (tp);
2070 down = mono_runtime_is_shutting_down ();
2071 if (!down && nt <= tp->min_threads)
2073 if (down || InterlockedCompareExchange (&tp->nthreads, nt - 1, nt) == nt) {
2074 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, -1);
2080 tp_finish_func (tp_hooks_user_data);
2087 g_assert_not_reached ();
2091 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
2093 *workerThreads = async_tp.max_threads - async_tp.busy_threads;
2094 *completionPortThreads = async_io_tp.max_threads - async_io_tp.busy_threads;
2098 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
2100 *workerThreads = async_tp.max_threads;
2101 *completionPortThreads = async_io_tp.max_threads;
2105 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
2107 *workerThreads = async_tp.min_threads;
2108 *completionPortThreads = async_io_tp.min_threads;
2112 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
2115 gint max_io_threads;
2117 max_threads = async_tp.max_threads;
2118 if (workerThreads <= 0 || workerThreads > max_threads)
2121 max_io_threads = async_io_tp.max_threads;
2122 if (completionPortThreads <= 0 || completionPortThreads > max_io_threads)
2125 InterlockedExchange (&async_tp.min_threads, workerThreads);
2126 InterlockedExchange (&async_io_tp.min_threads, completionPortThreads);
2127 if (workerThreads > async_tp.nthreads)
2128 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_tp, TRUE);
2129 if (completionPortThreads > async_io_tp.nthreads)
2130 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_io_tp, TRUE);
2135 ves_icall_System_Threading_ThreadPool_SetMaxThreads (gint workerThreads, gint completionPortThreads)
2138 gint min_io_threads;
2141 cpu_count = mono_cpu_count ();
2142 min_threads = async_tp.min_threads;
2143 if (workerThreads < min_threads || workerThreads < cpu_count)
2146 /* We don't really have the concept of completion ports. Do we care here? */
2147 min_io_threads = async_io_tp.min_threads;
2148 if (completionPortThreads < min_io_threads || completionPortThreads < cpu_count)
2151 InterlockedExchange (&async_tp.max_threads, workerThreads);
2152 InterlockedExchange (&async_io_tp.max_threads, completionPortThreads);
2157 * mono_install_threadpool_thread_hooks
2158 * @start_func: the function to be called right after a new threadpool thread is created. Can be NULL.
2159 * @finish_func: the function to be called right before a thredpool thread is exiting. Can be NULL.
2160 * @user_data: argument passed to @start_func and @finish_func.
2162 * @start_fun will be called right after a threadpool thread is created and @finish_func right before a threadpool thread exits.
2163 * The calls will be made from the thread itself.
2166 mono_install_threadpool_thread_hooks (MonoThreadPoolFunc start_func, MonoThreadPoolFunc finish_func, gpointer user_data)
2168 tp_start_func = start_func;
2169 tp_finish_func = finish_func;
2170 tp_hooks_user_data = user_data;
2174 * mono_install_threadpool_item_hooks
2175 * @begin_func: the function to be called before a threadpool work item processing starts.
2176 * @end_func: the function to be called after a threadpool work item is finished.
2177 * @user_data: argument passed to @begin_func and @end_func.
2179 * The calls will be made from the thread itself and from the same AppDomain
2180 * where the work item was executed.
2184 mono_install_threadpool_item_hooks (MonoThreadPoolItemFunc begin_func, MonoThreadPoolItemFunc end_func, gpointer user_data)
2186 tp_item_begin_func = begin_func;
2187 tp_item_end_func = end_func;
2188 tp_item_user_data = user_data;