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-2009 Novell, Inc (http://www.novell.com)
15 #define THREADS_PER_CPU 10 /* 8 + THREADS_PER_CPU * number of CPUs = max threads */
16 #define THREAD_EXIT_TIMEOUT 1000
17 #define INITIAL_QUEUE_LENGTH 128
19 #include <mono/metadata/domain-internals.h>
20 #include <mono/metadata/tabledefs.h>
21 #include <mono/metadata/threads.h>
22 #include <mono/metadata/threads-types.h>
23 #include <mono/metadata/threadpool-internals.h>
24 #include <mono/metadata/exception.h>
25 #include <mono/metadata/file-io.h>
26 #include <mono/metadata/monitor.h>
27 #include <mono/metadata/mono-mlist.h>
28 #include <mono/metadata/marshal.h>
29 #include <mono/metadata/mono-perfcounters.h>
30 #include <mono/metadata/socket-io.h>
31 #include <mono/io-layer/io-layer.h>
32 #include <mono/metadata/gc-internal.h>
33 #include <mono/utils/mono-time.h>
34 #include <mono/utils/mono-proclib.h>
36 #ifdef HAVE_SYS_TIME_H
39 #include <sys/types.h>
45 #ifdef HAVE_SYS_SOCKET_H
46 #include <sys/socket.h>
48 #include <mono/utils/mono-poll.h>
50 #include <sys/epoll.h>
53 #ifndef DISABLE_SOCKETS
54 #include "mono/io-layer/socket-wrappers.h"
57 #include "threadpool.h"
59 #define THREAD_WANTS_A_BREAK(t) ((t->state & (ThreadState_StopRequested | \
60 ThreadState_SuspendRequested)) != 0)
64 /* map of CounterSample.cs */
65 struct _MonoCounterSample {
68 gint64 counterFrequency;
69 gint64 systemFrequency;
71 gint64 timeStamp100nSec;
72 gint64 counterTimeStamp;
76 /* mono_thread_pool_init called */
79 static int pending_io_items;
82 CRITICAL_SECTION io_lock; /* access to sock_to_state */
85 MonoGHashTable *sock_to_state;
87 HANDLE new_sem; /* access to newpfd and write side of the pipe */
89 gboolean epoll_disabled;
95 static SocketIOData socket_io_data;
97 /* Keep in sync with the System.MonoAsyncCall class which provides GC tracking */
100 MonoMethodMessage *msg;
101 MonoMethod *cb_method;
102 MonoDelegate *cb_target;
106 /* This is a HANDLE, we use guint64 so the managed object layout remains constant */
107 /* THIS FIELD IS NOT USED ANY MORE. Remove it when we feel like breaking corlib compatibility with 2.6 */
112 CRITICAL_SECTION lock;
118 GQueue *idle_threads;
119 int idle_started; /* Have we started the idle threads? Interlocked */
120 /* min, max, n and busy -> Interlocked */
126 void (*async_invoke) (gpointer data);
127 void *pc_nitems; /* Performance counter for total number of items in added */
128 /* We don't need the rate here since we can compute the different ourselves */
129 /* void *perfc_rate; */
130 MonoCounterSample last_sample;
134 static ThreadPool async_tp;
135 static ThreadPool async_io_tp;
144 static void async_invoke_thread (gpointer data);
145 static void mono_async_invoke (MonoAsyncResult *ares);
146 static void threadpool_free_queue (ThreadPool *tp);
147 static void threadpool_append_job (ThreadPool *tp, MonoObject *ar);
148 static void *threadpool_queue_idle_thread (ThreadPool *tp, IdleThreadData *it);
149 static void threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer));
150 static void threadpool_start_idle_threads (ThreadPool *tp);
151 static void threadpool_kill_idle_threads (ThreadPool *tp);
153 static MonoClass *async_call_klass;
154 static MonoClass *socket_async_call_klass;
155 static MonoClass *process_async_call_klass;
158 static MonoThreadPoolFunc tp_start_func;
159 static MonoThreadPoolFunc tp_finish_func;
160 static gpointer tp_hooks_user_data;
161 static MonoThreadPoolItemFunc tp_item_begin_func;
162 static MonoThreadPoolItemFunc tp_item_end_func;
163 static gpointer tp_item_user_data;
165 #define INIT_POLLFD(a, b, c) {(a)->fd = b; (a)->events = c; (a)->revents = 0;}
174 AIO_OP_RECV_JUST_CALLBACK,
175 AIO_OP_SEND_JUST_CALLBACK,
180 #ifdef DISABLE_SOCKETS
181 #define socket_io_cleanup(x)
184 socket_io_cleanup (SocketIOData *data)
186 if (data->inited == 0)
189 EnterCriticalSection (&data->io_lock);
192 closesocket (data->pipe [0]);
193 closesocket (data->pipe [1]);
195 close (data->pipe [0]);
196 close (data->pipe [1]);
201 CloseHandle (data->new_sem);
202 data->new_sem = NULL;
203 mono_g_hash_table_destroy (data->sock_to_state);
204 data->sock_to_state = NULL;
205 EnterCriticalSection (&async_io_tp.lock);
206 threadpool_free_queue (&async_io_tp);
207 threadpool_kill_idle_threads (&async_io_tp);
208 LeaveCriticalSection (&async_io_tp.lock);
209 g_free (data->newpfd);
212 if (FALSE == data->epoll_disabled)
213 close (data->epollfd);
215 LeaveCriticalSection (&data->io_lock);
219 get_event_from_state (MonoSocketAsyncResult *state)
221 switch (state->operation) {
224 case AIO_OP_RECV_JUST_CALLBACK:
225 case AIO_OP_RECEIVEFROM:
226 case AIO_OP_READPIPE:
229 case AIO_OP_SEND_JUST_CALLBACK:
233 default: /* Should never happen */
234 g_print ("get_event_from_state: unknown value in switch!!!\n");
240 get_events_from_list (MonoMList *list)
242 MonoSocketAsyncResult *state;
245 while (list && (state = (MonoSocketAsyncResult *)mono_mlist_get_data (list))) {
246 events |= get_event_from_state (state);
247 list = mono_mlist_next (list);
253 #define ICALL_RECV(x) ves_icall_System_Net_Sockets_Socket_Receive_internal (\
254 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
255 x->socket_flags, &x->error);
257 #define ICALL_SEND(x) ves_icall_System_Net_Sockets_Socket_Send_internal (\
258 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
259 x->socket_flags, &x->error);
261 #endif /* !DISABLE_SOCKETS */
264 threadpool_jobs_inc (MonoObject *obj)
267 InterlockedIncrement (&obj->vtable->domain->threadpool_jobs);
271 threadpool_jobs_dec (MonoObject *obj)
273 MonoDomain *domain = obj->vtable->domain;
274 int remaining_jobs = InterlockedDecrement (&domain->threadpool_jobs);
275 if (remaining_jobs == 0 && domain->cleanup_semaphore) {
276 ReleaseSemaphore (domain->cleanup_semaphore, 1, NULL);
282 #ifndef DISABLE_SOCKETS
284 async_invoke_io_thread (gpointer data)
287 MonoInternalThread *thread;
288 const gchar *version;
289 IdleThreadData idle_data = {0};
291 idle_data.timeout = INFINITE;
292 idle_data.wait_handle = CreateEvent (NULL, FALSE, FALSE, NULL);
294 thread = mono_thread_internal_current ();
296 tp_start_func (tp_hooks_user_data);
298 version = mono_get_runtime_info ()->framework_version;
300 MonoSocketAsyncResult *state;
303 state = (MonoSocketAsyncResult *) data;
305 InterlockedDecrement (&pending_io_items);
307 switch (state->operation) {
309 state->total = ICALL_RECV (state);
312 state->total = ICALL_SEND (state);
316 /* worker threads invokes methods in different domains,
317 * so we need to set the right domain here */
318 domain = ((MonoObject *)ar)->vtable->domain;
322 if (domain->state == MONO_APPDOMAIN_UNLOADED || domain->state == MONO_APPDOMAIN_UNLOADING) {
323 threadpool_jobs_dec ((MonoObject *)ar);
326 mono_thread_push_appdomain_ref (domain);
327 if (threadpool_jobs_dec ((MonoObject *)ar)) {
329 mono_thread_pop_appdomain_ref ();
332 if (mono_domain_set (domain, FALSE)) {
335 if (tp_item_begin_func)
336 tp_item_begin_func (tp_item_user_data);
337 mono_async_invoke (ar);
338 if (tp_item_end_func)
339 tp_item_end_func (tp_item_user_data);
341 ac = (ASyncCall *) ar->object_data;
342 if (ac->msg->exc != NULL)
343 mono_unhandled_exception (ac->msg->exc);
345 mono_domain_set (mono_get_root_domain (), TRUE);
347 mono_thread_pop_appdomain_ref ();
348 InterlockedDecrement (&async_io_tp.busy_threads);
349 /* If the callee changes the background status, set it back to TRUE */
350 if (*version != '1' && !mono_thread_test_state (thread , ThreadState_Background))
351 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
355 data = threadpool_queue_idle_thread (&async_io_tp, &idle_data);
356 while (!idle_data.die && !data) {
358 wr = WaitForSingleObjectEx (idle_data.wait_handle, idle_data.timeout, TRUE);
359 if (THREAD_WANTS_A_BREAK (thread))
360 mono_thread_interruption_checkpoint ();
362 if (wr != WAIT_TIMEOUT && wr != WAIT_IO_COMPLETION) {
363 data = idle_data.data;
364 idle_data.data = NULL;
365 break; /* We have to exit */
370 InterlockedDecrement (&async_io_tp.nthreads);
371 CloseHandle (idle_data.wait_handle);
372 idle_data.wait_handle = NULL;
374 tp_finish_func (tp_hooks_user_data);
378 InterlockedIncrement (&async_io_tp.busy_threads);
381 g_assert_not_reached ();
385 process_io_event (MonoMList *list, int event)
387 MonoSocketAsyncResult *state;
393 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
394 if (get_event_from_state (state) == event)
397 list = mono_mlist_next (list);
401 oldlist = mono_mlist_remove_item (oldlist, list);
403 g_print ("Dispatching event %d on socket %p\n", event, state->handle);
405 InterlockedIncrement (&pending_io_items);
406 threadpool_append_job (&async_io_tp, (MonoObject *) state);
413 mark_bad_fds (mono_pollfd *pfds, int nfds)
419 for (i = 0; i < nfds; i++) {
424 ret = mono_poll (pfd, 1, 0);
425 if (ret == -1 && errno == EBADF) {
426 pfd->revents |= MONO_POLLNVAL;
428 } else if (ret == 1) {
437 socket_io_poll_main (gpointer p)
439 #define INITIAL_POLLFD_SIZE 1024
440 #define POLL_ERRORS (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL)
441 SocketIOData *data = p;
446 MonoInternalThread *thread;
448 thread = mono_thread_internal_current ();
450 allocated = INITIAL_POLLFD_SIZE;
451 pfds = g_new0 (mono_pollfd, allocated);
452 INIT_POLLFD (pfds, data->pipe [0], MONO_POLLIN);
453 for (i = 1; i < allocated; i++)
454 INIT_POLLFD (&pfds [i], -1, 0);
464 if (THREAD_WANTS_A_BREAK (thread))
465 mono_thread_interruption_checkpoint ();
468 nsock = mono_poll (pfds, maxfd, -1);
469 } while (nsock == -1 && errno == EINTR);
472 * Apart from EINTR, we only check EBADF, for the rest:
473 * EINVAL: mono_poll() 'protects' us from descriptor
474 * numbers above the limit if using select() by marking
475 * then as MONO_POLLERR. If a system poll() is being
476 * used, the number of descriptor we're passing will not
477 * be over sysconf(_SC_OPEN_MAX), as the error would have
478 * happened when opening.
480 * EFAULT: we own the memory pointed by pfds.
481 * ENOMEM: we're doomed anyway
485 if (nsock == -1 && errno == EBADF) {
486 pfds->revents = 0; /* Just in case... */
487 nsock = mark_bad_fds (pfds, maxfd);
490 if ((pfds->revents & POLL_ERRORS) != 0) {
491 /* We're supposed to die now, as the pipe has been closed */
493 socket_io_cleanup (data);
497 /* Got a new socket */
498 if ((pfds->revents & MONO_POLLIN) != 0) {
501 for (i = 1; i < allocated; i++) {
503 if (pfd->fd == -1 || pfd->fd == data->newpfd->fd)
507 if (i == allocated) {
512 allocated = allocated * 2;
513 pfds = g_renew (mono_pollfd, oldfd, allocated);
515 for (; i < allocated; i++)
516 INIT_POLLFD (&pfds [i], -1, 0);
519 nread = read (data->pipe [0], one, 1);
521 nread = recv ((SOCKET) data->pipe [0], one, 1, 0);
525 return; /* we're closed */
528 INIT_POLLFD (&pfds [i], data->newpfd->fd, data->newpfd->events);
529 ReleaseSemaphore (data->new_sem, 1, NULL);
538 EnterCriticalSection (&data->io_lock);
539 if (data->inited == 0) {
541 LeaveCriticalSection (&data->io_lock);
542 return; /* cleanup called */
545 for (i = 1; i < maxfd && nsock > 0; i++) {
547 if (pfd->fd == -1 || pfd->revents == 0)
551 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
552 if (list != NULL && (pfd->revents & (MONO_POLLIN | POLL_ERRORS)) != 0) {
553 list = process_io_event (list, MONO_POLLIN);
556 if (list != NULL && (pfd->revents & (MONO_POLLOUT | POLL_ERRORS)) != 0) {
557 list = process_io_event (list, MONO_POLLOUT);
561 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (pfd->fd), list);
562 pfd->events = get_events_from_list (list);
564 mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
570 LeaveCriticalSection (&data->io_lock);
575 #define EPOLL_ERRORS (EPOLLERR | EPOLLHUP)
577 socket_io_epoll_main (gpointer p)
581 MonoInternalThread *thread;
582 struct epoll_event *events, *evt;
583 const int nevents = 512;
587 epollfd = data->epollfd;
588 thread = mono_thread_internal_current ();
589 events = g_new0 (struct epoll_event, nevents);
594 if (THREAD_WANTS_A_BREAK (thread))
595 mono_thread_interruption_checkpoint ();
598 g_print ("epoll_wait init\n");
600 ready = epoll_wait (epollfd, events, nevents, -1);
604 g_print ("epoll_wait end with %d ready sockets (%d %s).\n", ready, err, (err) ? g_strerror (err) : "");
608 } while (ready == -1 && errno == EINTR);
614 g_warning ("epoll_wait: %d %s\n", err, g_strerror (err));
620 EnterCriticalSection (&data->io_lock);
621 if (data->inited == 0) {
623 g_print ("data->inited == 0\n");
627 return; /* cleanup called */
630 for (i = 0; i < ready; i++) {
636 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
638 g_print ("Event %d on %d list length: %d\n", evt->events, fd, mono_mlist_length (list));
640 if (list != NULL && (evt->events & (EPOLLIN | EPOLL_ERRORS)) != 0) {
641 list = process_io_event (list, MONO_POLLIN);
644 if (list != NULL && (evt->events & (EPOLLOUT | EPOLL_ERRORS)) != 0) {
645 list = process_io_event (list, MONO_POLLOUT);
649 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (fd), list);
650 evt->events = get_events_from_list (list);
652 g_print ("MOD %d to %d\n", fd, evt->events);
654 if (epoll_ctl (epollfd, EPOLL_CTL_MOD, fd, evt)) {
655 if (epoll_ctl (epollfd, EPOLL_CTL_ADD, fd, evt) == -1) {
658 g_message ("epoll_ctl(MOD): %d %s fd: %d events: %d", err, g_strerror (err), fd, evt->events);
664 mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (fd));
666 g_print ("DEL %d\n", fd);
668 epoll_ctl (epollfd, EPOLL_CTL_DEL, fd, evt);
671 LeaveCriticalSection (&data->io_lock);
677 * select/poll wake up when a socket is closed, but epoll just removes
678 * the socket from its internal list without notification.
681 mono_thread_pool_remove_socket (int sock)
683 MonoMList *list, *next;
684 MonoSocketAsyncResult *state;
686 if (socket_io_data.inited == FALSE)
689 EnterCriticalSection (&socket_io_data.io_lock);
690 list = mono_g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
692 mono_g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
694 LeaveCriticalSection (&socket_io_data.io_lock);
697 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
698 if (state->operation == AIO_OP_RECEIVE)
699 state->operation = AIO_OP_RECV_JUST_CALLBACK;
700 else if (state->operation == AIO_OP_SEND)
701 state->operation = AIO_OP_SEND_JUST_CALLBACK;
703 next = mono_mlist_remove_item (list, list);
704 list = process_io_event (list, MONO_POLLIN);
706 process_io_event (list, MONO_POLLOUT);
714 connect_hack (gpointer x)
716 struct sockaddr_in *addr = (struct sockaddr_in *) x;
719 while (connect ((SOCKET) socket_io_data.pipe [1], (SOCKADDR *) addr, sizeof (struct sockaddr_in))) {
722 g_warning ("Error initializing async. sockets %d.\n", WSAGetLastError ());
723 g_assert (WSAGetLastError ());
730 socket_io_init (SocketIOData *data)
733 struct sockaddr_in server;
734 struct sockaddr_in client;
740 inited = InterlockedCompareExchange (&data->inited, -1, -1);
744 EnterCriticalSection (&data->io_lock);
745 inited = InterlockedCompareExchange (&data->inited, -1, -1);
747 LeaveCriticalSection (&data->io_lock);
752 data->epoll_disabled = (g_getenv ("MONO_DISABLE_AIO") != NULL);
753 if (FALSE == data->epoll_disabled) {
754 data->epollfd = epoll_create (256);
755 data->epoll_disabled = (data->epollfd == -1);
756 if (data->epoll_disabled && g_getenv ("MONO_DEBUG"))
757 g_message ("epoll_create() failed. Using plain poll().");
762 data->epoll_disabled = TRUE;
766 if (data->epoll_disabled) {
767 if (pipe (data->pipe) != 0) {
777 srv = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
778 g_assert (srv != INVALID_SOCKET);
779 data->pipe [1] = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
780 g_assert (data->pipe [1] != INVALID_SOCKET);
782 server.sin_family = AF_INET;
783 server.sin_addr.s_addr = inet_addr ("127.0.0.1");
785 if (bind (srv, (SOCKADDR *) &server, sizeof (server))) {
786 g_print ("%d\n", WSAGetLastError ());
790 len = sizeof (server);
791 getsockname (srv, (SOCKADDR *) &server, &len);
793 mono_thread_create (mono_get_root_domain (), connect_hack, &server);
794 len = sizeof (server);
795 data->pipe [0] = accept (srv, (SOCKADDR *) &client, &len);
796 g_assert (data->pipe [0] != INVALID_SOCKET);
799 data->sock_to_state = mono_g_hash_table_new_type (g_direct_hash, g_direct_equal, MONO_HASH_VALUE_GC);
800 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_io_tp, TRUE);
802 if (data->epoll_disabled) {
803 data->new_sem = CreateSemaphore (NULL, 1, 1, NULL);
804 g_assert (data->new_sem != NULL);
806 if (data->epoll_disabled) {
807 mono_thread_create_internal (mono_get_root_domain (), socket_io_poll_main, data, TRUE);
811 mono_thread_create_internal (mono_get_root_domain (), socket_io_epoll_main, data, TRUE);
814 InterlockedCompareExchange (&data->inited, 1, 0);
815 LeaveCriticalSection (&data->io_lock);
819 socket_io_add_poll (MonoSocketAsyncResult *state)
824 SocketIOData *data = &socket_io_data;
827 #if defined(PLATFORM_MACOSX) || defined(PLATFORM_BSD) || defined(HOST_WIN32) || defined(PLATFORM_SOLARIS)
828 /* select() for connect() does not work well on the Mac. Bug #75436. */
829 /* Bug #77637 for the BSD 6 case */
830 /* Bug #78888 for the Windows case */
831 if (state->operation == AIO_OP_CONNECT && state->blocking == TRUE) {
832 threadpool_append_job (&async_io_tp, (MonoObject *) state);
836 WaitForSingleObject (data->new_sem, INFINITE);
837 if (data->newpfd == NULL)
838 data->newpfd = g_new0 (mono_pollfd, 1);
840 EnterCriticalSection (&data->io_lock);
841 /* FIXME: 64 bit issue: handle can be a pointer on windows? */
842 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (state->handle));
844 list = mono_mlist_alloc ((MonoObject*)state);
846 list = mono_mlist_append (list, (MonoObject*)state);
849 events = get_events_from_list (list);
850 INIT_POLLFD (data->newpfd, GPOINTER_TO_INT (state->handle), events);
851 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (state->handle), list);
852 LeaveCriticalSection (&data->io_lock);
853 *msg = (char) state->operation;
855 w = write (data->pipe [1], msg, 1);
858 send ((SOCKET) data->pipe [1], msg, 1, 0);
864 socket_io_add_epoll (MonoSocketAsyncResult *state)
867 SocketIOData *data = &socket_io_data;
868 struct epoll_event event;
872 memset (&event, 0, sizeof (struct epoll_event));
873 fd = GPOINTER_TO_INT (state->handle);
874 EnterCriticalSection (&data->io_lock);
875 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
877 list = mono_mlist_alloc ((MonoObject*)state);
878 epoll_op = EPOLL_CTL_ADD;
880 list = mono_mlist_append (list, (MonoObject*)state);
881 epoll_op = EPOLL_CTL_MOD;
884 ievt = get_events_from_list (list);
885 if ((ievt & MONO_POLLIN) != 0)
886 event.events |= EPOLLIN;
887 if ((ievt & MONO_POLLOUT) != 0)
888 event.events |= EPOLLOUT;
890 mono_g_hash_table_replace (data->sock_to_state, state->handle, list);
893 g_print ("%s %d with %d\n", epoll_op == EPOLL_CTL_ADD ? "ADD" : "MOD", fd, event.events);
895 if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
897 if (epoll_op == EPOLL_CTL_ADD && err == EEXIST) {
898 epoll_op = EPOLL_CTL_MOD;
899 if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
900 g_message ("epoll_ctl(MOD): %d %s\n", err, g_strerror (err));
905 LeaveCriticalSection (&data->io_lock);
911 socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
913 socket_io_init (&socket_io_data);
914 MONO_OBJECT_SETREF (state, ares, ares);
916 if (socket_io_data.epoll_disabled == FALSE) {
917 if (socket_io_add_epoll (state))
921 socket_io_add_poll (state);
925 socket_io_filter (MonoObject *target, MonoObject *state)
928 MonoSocketAsyncResult *sock_res = (MonoSocketAsyncResult *) state;
931 if (target == NULL || state == NULL)
934 if (socket_async_call_klass == NULL) {
935 klass = target->vtable->klass;
936 /* Check if it's SocketAsyncCall in System.Net.Sockets
937 * FIXME: check the assembly is signed correctly for extra care
939 if (klass->name [0] == 'S' && strcmp (klass->name, "SocketAsyncCall") == 0
940 && strcmp (mono_image_get_name (klass->image), "System") == 0
941 && klass->nested_in && strcmp (klass->nested_in->name, "Socket") == 0)
942 socket_async_call_klass = klass;
945 if (process_async_call_klass == NULL) {
946 klass = target->vtable->klass;
947 /* Check if it's AsyncReadHandler in System.Diagnostics.Process
948 * FIXME: check the assembly is signed correctly for extra care
950 if (klass->name [0] == 'A' && strcmp (klass->name, "AsyncReadHandler") == 0
951 && strcmp (mono_image_get_name (klass->image), "System") == 0
952 && klass->nested_in && strcmp (klass->nested_in->name, "Process") == 0)
953 process_async_call_klass = klass;
955 /* return both when socket_async_call_klass has not been seen yet and when
956 * the object is not an instance of the class.
958 if (target->vtable->klass != socket_async_call_klass && target->vtable->klass != process_async_call_klass)
961 op = sock_res->operation;
962 if (op < AIO_OP_FIRST || op >= AIO_OP_LAST)
967 #endif /* !DISABLE_SOCKETS */
970 mono_async_invoke (MonoAsyncResult *ares)
972 ASyncCall *ac = (ASyncCall *)ares->object_data;
973 MonoObject *res, *exc = NULL;
974 MonoArray *out_args = NULL;
975 HANDLE wait_event = NULL;
977 if (ares->execution_context) {
978 /* use captured ExecutionContext (if available) */
979 MONO_OBJECT_SETREF (ares, original_context, mono_thread_get_execution_context ());
980 mono_thread_set_execution_context (ares->execution_context);
982 ares->original_context = NULL;
986 res = mono_message_invoke (ares->async_delegate, ac->msg, &exc, &out_args);
987 MONO_OBJECT_SETREF (ac, res, res);
988 MONO_OBJECT_SETREF (ac, msg->exc, exc);
989 MONO_OBJECT_SETREF (ac, out_args, out_args);
991 mono_monitor_enter ((MonoObject *) ares);
993 if (ares->handle != NULL)
994 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
995 mono_monitor_exit ((MonoObject *) ares);
996 /* notify listeners */
997 if (wait_event != NULL)
998 SetEvent (wait_event);
1000 /* call async callback if cb_method != null*/
1001 if (ac->cb_method) {
1002 MonoObject *exc = NULL;
1004 mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &exc);
1005 /* 'exc' will be the previous ac->msg->exc if not NULL and not
1006 * catched. If catched, this will be set to NULL and the
1007 * exception will not be printed. */
1008 MONO_OBJECT_SETREF (ac->msg, exc, exc);
1011 /* restore original thread execution context if flow isn't suppressed, i.e. non null */
1012 if (ares->original_context) {
1013 mono_thread_set_execution_context (ares->original_context);
1014 ares->original_context = NULL;
1020 threadpool_start_idle_threads (ThreadPool *tp)
1025 needed = (int) InterlockedCompareExchange (&tp->min_threads, 0, -1);
1027 existing = (int) InterlockedCompareExchange (&tp->nthreads, 0, -1);
1028 if (existing >= needed)
1030 InterlockedIncrement (&tp->nthreads);
1031 mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, NULL, TRUE);
1032 SleepEx (250, TRUE);
1037 threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer))
1039 memset (tp, 0, sizeof (ThreadPool));
1040 InitializeCriticalSection (&tp->lock);
1041 tp->min_threads = min_threads;
1042 tp->max_threads = max_threads;
1043 tp->async_invoke = async_invoke;
1044 tp->idle_threads = g_queue_new ();
1048 init_perf_counter (const char *category, const char *counter)
1050 MonoString *category_str;
1051 MonoString *counter_str;
1052 MonoString *machine;
1057 if (category == NULL || counter == NULL)
1059 root = mono_get_root_domain ();
1060 category_str = mono_string_new (root, category);
1061 counter_str = mono_string_new (root, counter);
1062 machine = mono_string_new (root, ".");
1063 return mono_perfcounter_get_impl (category_str, counter_str, NULL, machine, &type, &custom);
1067 mono_thread_pool_init ()
1069 int threads_per_cpu = THREADS_PER_CPU;
1073 if ((int) InterlockedCompareExchange (&tp_inited, 1, 0) == 1)
1076 MONO_GC_REGISTER_ROOT (socket_io_data.sock_to_state);
1077 InitializeCriticalSection (&socket_io_data.io_lock);
1078 if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
1079 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
1080 if (threads_per_cpu < THREADS_PER_CPU)
1081 threads_per_cpu = THREADS_PER_CPU;
1084 cpu_count = mono_cpu_count ();
1085 n = 8 + 2 * cpu_count; /* 8 is minFreeThreads for ASP.NET */
1086 threadpool_init (&async_tp, n, n + threads_per_cpu * cpu_count, async_invoke_thread);
1087 #ifndef DISABLE_SOCKETS
1088 threadpool_init (&async_io_tp, 2 * cpu_count, 8 * cpu_count, async_invoke_io_thread);
1091 async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
1092 g_assert (async_call_klass);
1094 async_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "Work Items Added");
1095 g_assert (async_tp.pc_nitems);
1096 mono_perfcounter_get_sample (async_tp.pc_nitems, FALSE, &async_tp.last_sample);
1098 async_io_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "IO Work Items Added");
1099 g_assert (async_io_tp.pc_nitems);
1100 mono_perfcounter_get_sample (async_io_tp.pc_nitems, FALSE, &async_io_tp.last_sample);
1104 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
1107 MonoDomain *domain = mono_domain_get ();
1108 MonoAsyncResult *ares;
1111 ac = (ASyncCall*)mono_object_new (mono_domain_get (), async_call_klass);
1112 MONO_OBJECT_SETREF (ac, msg, msg);
1113 MONO_OBJECT_SETREF (ac, state, state);
1115 if (async_callback) {
1116 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
1117 MONO_OBJECT_SETREF (ac, cb_target, async_callback);
1120 ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
1121 MONO_OBJECT_SETREF (ares, async_delegate, target);
1123 #ifndef DISABLE_SOCKETS
1124 if (socket_io_filter (target, state)) {
1125 socket_io_add (ares, (MonoSocketAsyncResult *) state);
1129 if (InterlockedCompareExchange (&async_tp.idle_started, 1, 0) == 0)
1130 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_tp, TRUE);
1132 threadpool_append_job (&async_tp, (MonoObject *) ares);
1137 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1145 /* check if already finished */
1146 mono_monitor_enter ((MonoObject *) ares);
1148 if (ares->endinvoke_called) {
1149 *exc = (MonoObject *)mono_exception_from_name (mono_defaults.corlib, "System",
1150 "InvalidOperationException");
1151 mono_monitor_exit ((MonoObject *) ares);
1155 ares->endinvoke_called = 1;
1156 /* wait until we are really finished */
1157 if (!ares->completed) {
1158 if (ares->handle == NULL) {
1159 wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1160 g_assert(wait_event != 0);
1161 MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), wait_event));
1163 wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
1165 mono_monitor_exit ((MonoObject *) ares);
1166 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
1168 mono_monitor_exit ((MonoObject *) ares);
1171 ac = (ASyncCall *) ares->object_data;
1172 g_assert (ac != NULL);
1173 *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1174 *out_args = ac->out_args;
1180 threadpool_kill_idle_threads (ThreadPool *tp)
1184 if (!tp || !tp->idle_threads)
1187 while ((it = g_queue_pop_head (tp->idle_threads)) != NULL) {
1190 SetEvent (it->wait_handle);
1192 g_queue_free (tp->idle_threads);
1193 tp->idle_threads = NULL;
1197 mono_thread_pool_cleanup (void)
1199 EnterCriticalSection (&async_tp.lock);
1200 threadpool_free_queue (&async_tp);
1201 threadpool_kill_idle_threads (&async_tp);
1202 LeaveCriticalSection (&async_tp.lock);
1203 socket_io_cleanup (&socket_io_data); /* Empty when DISABLE_SOCKETS is defined */
1204 /* Do we want/need these?
1205 DeleteCriticalSection (&async_tp.lock);
1206 DeleteCriticalSection (&async_tp.table_lock);
1207 DeleteCriticalSection (&socket_io_data.io_lock);
1212 null_array (MonoArray *a, int first, int last)
1214 /* We must null the old array because it might
1215 contain cross-appdomain references, which
1216 will crash the GC when the domains are
1218 memset (mono_array_addr (a, MonoObject*, first), 0, sizeof (MonoObject*) * (last - first));
1221 /* Caller must enter &tp->lock */
1223 dequeue_job_nolock (ThreadPool *tp)
1228 if (!tp->array || tp->first_elem == tp->next_elem)
1230 ar = mono_array_get (tp->array, MonoObject*, tp->first_elem);
1231 mono_array_set (tp->array, MonoObject*, tp->first_elem, NULL);
1233 count = tp->next_elem - tp->first_elem;
1234 /* reduce the size of the array if it's mostly empty */
1235 if (mono_array_length (tp->array) > INITIAL_QUEUE_LENGTH && count < (mono_array_length (tp->array) / 3)) {
1236 MonoArray *newa = mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, mono_array_length (tp->array) / 2);
1237 mono_array_memcpy_refs (newa, 0, tp->array, tp->first_elem, count);
1238 null_array (tp->array, tp->first_elem, tp->next_elem);
1241 tp->next_elem = count;
1246 /* Call after entering &tp->lock */
1248 signal_idle_threads (ThreadPool *tp)
1254 njobs = tp->next_elem - tp->first_elem;
1255 while (njobs > 0 && (it = g_queue_pop_head (tp->idle_threads)) != NULL) {
1256 it->data = dequeue_job_nolock (tp);
1257 if (it->data == NULL)
1258 break; /* Should never happen */
1261 it->timeout = INFINITE;
1262 SetEvent (it->wait_handle);
1267 /* Call after entering &tp->lock */
1269 threadpool_start_thread (ThreadPool *tp, gpointer arg)
1274 max = (gint) InterlockedCompareExchange (&tp->max_threads, 0, -1);
1275 n = (gint) InterlockedCompareExchange (&tp->nthreads, 0, -1);
1278 InterlockedIncrement (&tp->nthreads);
1279 mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, arg, TRUE);
1285 get_queue_name (ThreadPool *tp)
1287 if (tp == &async_tp)
1289 if (tp == &async_io_tp)
1296 threadpool_queue_idle_thread (ThreadPool *tp, IdleThreadData *it)
1299 MonoCounterSample sample;
1302 gpointer result = NULL;
1303 CRITICAL_SECTION *cs = &tp->lock;
1305 EnterCriticalSection (cs);
1306 if (tp->idle_threads == NULL) {
1308 LeaveCriticalSection (cs);
1309 return NULL; /* We are shutting down */
1312 if (mono_100ns_ticks () - tp->last_sample.timeStamp > 10000 * 1000) {
1313 float elapsed_ticks;
1314 mono_perfcounter_get_sample (tp->pc_nitems, FALSE, &sample);
1316 elapsed_ticks = (float) (sample.timeStamp - tp->last_sample.timeStamp);
1317 rate = ((float) (sample.rawValue - tp->last_sample.rawValue)) / elapsed_ticks * 10000000;
1318 printf ("Queue: %s NThreads: %d Rate: %.2f Total items: %lld Time(ms): %.2f\n", get_queue_name (tp),
1319 InterlockedCompareExchange (&tp->nthreads, 0, -1), rate,
1320 sample.rawValue - tp->last_sample.rawValue, elapsed_ticks / 10000);
1321 memcpy (&tp->last_sample, &sample, sizeof (sample));
1325 it->data = result = dequeue_job_nolock (tp);
1326 if (result != NULL) {
1327 signal_idle_threads (tp);
1330 min = (gint) InterlockedCompareExchange (&tp->min_threads, 0, -1);
1331 n = (gint) InterlockedCompareExchange (&tp->nthreads, 0, -1);
1333 g_queue_push_tail (tp->idle_threads, it);
1335 /* TODO: figure out when threads should be told to die */
1336 /* it->die = TRUE; */
1337 g_queue_push_tail (tp->idle_threads, it);
1340 LeaveCriticalSection (cs);
1345 threadpool_append_job (ThreadPool *tp, MonoObject *ar)
1347 CRITICAL_SECTION *cs;
1350 threadpool_jobs_inc (ar);
1351 EnterCriticalSection (cs);
1352 if (tp->idle_threads == NULL) {
1353 LeaveCriticalSection (cs);
1354 return; /* We are shutting down */
1356 if (ar->vtable->domain->state == MONO_APPDOMAIN_UNLOADING ||
1357 ar->vtable->domain->state == MONO_APPDOMAIN_UNLOADED) {
1358 LeaveCriticalSection (cs);
1362 mono_perfcounter_update_value (tp->pc_nitems, TRUE, 1);
1363 if (tp->array && (tp->next_elem < mono_array_length (tp->array))) {
1364 mono_array_setref (tp->array, tp->next_elem, ar);
1366 if (signal_idle_threads (tp) > 0 && threadpool_start_thread (tp, ar)) {
1368 mono_array_setref (tp->array, tp->next_elem, NULL);
1370 LeaveCriticalSection (cs);
1375 MONO_GC_REGISTER_ROOT (tp->array);
1376 tp->array = mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, INITIAL_QUEUE_LENGTH);
1378 int count = tp->next_elem - tp->first_elem;
1379 /* slide the array or create a larger one if it's full */
1380 if (tp->first_elem) {
1381 mono_array_memcpy_refs (tp->array, 0, tp->array, tp->first_elem, count);
1382 null_array (tp->array, count, tp->next_elem);
1384 MonoArray *newa = mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, mono_array_length (tp->array) * 2);
1385 mono_array_memcpy_refs (newa, 0, tp->array, tp->first_elem, count);
1386 null_array (tp->array, count, tp->next_elem);
1390 tp->next_elem = count;
1392 mono_array_setref (tp->array, tp->next_elem, ar);
1394 if (signal_idle_threads (tp) > 0 && threadpool_start_thread (tp, ar)) {
1396 mono_array_setref (tp->array, tp->next_elem, NULL);
1398 LeaveCriticalSection (cs);
1403 threadpool_clear_queue (ThreadPool *tp, MonoDomain *domain)
1406 EnterCriticalSection (&tp->lock);
1408 for (i = tp->first_elem; i < tp->next_elem; ++i) {
1409 MonoObject *obj = mono_array_get (tp->array, MonoObject*, i);
1410 if (obj->vtable->domain == domain) {
1411 mono_array_set (tp->array, MonoObject*, i, NULL);
1412 InterlockedDecrement (&domain->threadpool_jobs);
1419 for (i = tp->first_elem; i < tp->next_elem; ++i) {
1420 MonoObject *obj = mono_array_get (tp->array, MonoObject*, i);
1422 mono_array_set (tp->array, MonoObject*, idx++, obj);
1425 tp->next_elem = count;
1427 LeaveCriticalSection (&tp->lock);
1431 * Clean up the threadpool of all domain jobs.
1432 * Can only be called as part of the domain unloading process as
1433 * it will wait for all jobs to be visible to the interruption code.
1436 mono_thread_pool_remove_domain_jobs (MonoDomain *domain, int timeout)
1440 guint32 start_time = 0;
1442 g_assert (domain->state == MONO_APPDOMAIN_UNLOADING);
1444 threadpool_clear_queue (&async_tp, domain);
1445 threadpool_clear_queue (&async_io_tp, domain);
1448 * There might be some threads out that could be about to execute stuff from the given domain.
1449 * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
1451 sem_handle = CreateSemaphore (NULL, 0, 1, NULL);
1453 domain->cleanup_semaphore = sem_handle;
1455 * The memory barrier here is required to have global ordering between assigning to cleanup_semaphone
1456 * and reading threadpool_jobs.
1457 * Otherwise this thread could read a stale version of threadpool_jobs and wait forever.
1459 mono_memory_write_barrier ();
1461 if (domain->threadpool_jobs && timeout != -1)
1462 start_time = mono_msec_ticks ();
1463 while (domain->threadpool_jobs) {
1464 WaitForSingleObject (sem_handle, timeout);
1465 if (timeout != -1 && (mono_msec_ticks () - start_time) > timeout) {
1471 domain->cleanup_semaphore = NULL;
1472 CloseHandle (sem_handle);
1477 threadpool_free_queue (ThreadPool *tp)
1480 null_array (tp->array, tp->first_elem, tp->next_elem);
1482 tp->first_elem = tp->next_elem = 0;
1486 mono_thread_pool_is_queue_array (MonoArray *o)
1488 return o == async_tp.array || o == async_io_tp.array;
1492 async_invoke_thread (gpointer data)
1495 MonoInternalThread *thread;
1496 const gchar *version;
1497 IdleThreadData idle_data = {0};
1499 idle_data.timeout = INFINITE;
1500 idle_data.wait_handle = CreateEvent (NULL, FALSE, FALSE, NULL);
1502 thread = mono_thread_internal_current ();
1504 tp_start_func (tp_hooks_user_data);
1505 version = mono_get_runtime_info ()->framework_version;
1507 MonoAsyncResult *ar;
1509 ar = (MonoAsyncResult *) data;
1511 /* worker threads invokes methods in different domains,
1512 * so we need to set the right domain here */
1513 domain = ((MonoObject *)ar)->vtable->domain;
1517 if (domain->state == MONO_APPDOMAIN_UNLOADED || domain->state == MONO_APPDOMAIN_UNLOADING) {
1518 threadpool_jobs_dec ((MonoObject *)ar);
1521 mono_thread_push_appdomain_ref (domain);
1522 if (threadpool_jobs_dec ((MonoObject *)ar)) {
1524 mono_thread_pop_appdomain_ref ();
1528 if (mono_domain_set (domain, FALSE)) {
1529 /* ASyncCall *ac; */
1531 if (tp_item_begin_func)
1532 tp_item_begin_func (tp_item_user_data);
1533 mono_async_invoke (ar);
1534 if (tp_item_end_func)
1535 tp_item_end_func (tp_item_user_data);
1537 ac = (ASyncCall *) ar->object_data;
1538 if (ac->msg->exc != NULL)
1539 mono_unhandled_exception (ac->msg->exc);
1541 mono_domain_set (mono_get_root_domain (), TRUE);
1543 mono_thread_pop_appdomain_ref ();
1544 InterlockedDecrement (&async_tp.busy_threads);
1545 /* If the callee changes the background status, set it back to TRUE */
1546 if (*version != '1' && !mono_thread_test_state (thread , ThreadState_Background))
1547 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
1550 data = threadpool_queue_idle_thread (&async_tp, &idle_data);
1551 while (!idle_data.die && !data) {
1553 wr = WaitForSingleObjectEx (idle_data.wait_handle, idle_data.timeout, TRUE);
1554 if (THREAD_WANTS_A_BREAK (thread))
1555 mono_thread_interruption_checkpoint ();
1557 if (wr != WAIT_TIMEOUT && wr != WAIT_IO_COMPLETION) {
1558 data = idle_data.data;
1559 break; /* We have to exit */
1562 idle_data.data = NULL;
1565 InterlockedDecrement (&async_tp.nthreads);
1566 CloseHandle (idle_data.wait_handle);
1567 idle_data.wait_handle = NULL;
1569 tp_finish_func (tp_hooks_user_data);
1573 InterlockedIncrement (&async_tp.busy_threads);
1576 g_assert_not_reached ();
1580 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
1584 MONO_ARCH_SAVE_REGS;
1586 busy = (gint) InterlockedCompareExchange (&async_tp.busy_threads, 0, -1);
1587 busy_io = (gint) InterlockedCompareExchange (&async_io_tp.busy_threads, 0, -1);
1588 *workerThreads = async_tp.max_threads - busy;
1589 *completionPortThreads = async_io_tp.max_threads - busy_io;
1593 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
1595 MONO_ARCH_SAVE_REGS;
1597 *workerThreads = (gint) InterlockedCompareExchange (&async_tp.max_threads, 0, -1);
1598 *completionPortThreads = (gint) InterlockedCompareExchange (&async_io_tp.max_threads, 0, -1);
1602 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
1604 gint workers, workers_io;
1606 MONO_ARCH_SAVE_REGS;
1608 workers = (gint) InterlockedCompareExchange (&async_tp.min_threads, 0, -1);
1609 workers_io = (gint) InterlockedCompareExchange (&async_io_tp.min_threads, 0, -1);
1611 *workerThreads = workers;
1612 *completionPortThreads = workers_io;
1616 start_idle_threads (void)
1618 threadpool_start_idle_threads (&async_tp);
1622 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
1627 MONO_ARCH_SAVE_REGS;
1629 max_threads = InterlockedCompareExchange (&async_tp.max_threads, -1, -1);
1630 if (workerThreads <= 0 || workerThreads > max_threads)
1633 max_io_threads = InterlockedCompareExchange (&async_io_tp.max_threads, -1, -1);
1634 if (completionPortThreads <= 0 || completionPortThreads > max_io_threads)
1637 InterlockedExchange (&async_tp.min_threads, workerThreads);
1638 InterlockedExchange (&async_io_tp.min_threads, completionPortThreads);
1639 mono_thread_create_internal (mono_get_root_domain (), start_idle_threads, NULL, TRUE);
1644 ves_icall_System_Threading_ThreadPool_SetMaxThreads (gint workerThreads, gint completionPortThreads)
1650 MONO_ARCH_SAVE_REGS;
1652 cpu_count = mono_cpu_count ();
1653 min_threads = InterlockedCompareExchange (&async_tp.min_threads, -1, -1);
1654 if (workerThreads < min_threads || workerThreads < cpu_count)
1657 /* We don't really have the concept of completion ports. Do we care here? */
1658 min_io_threads = InterlockedCompareExchange (&async_io_tp.min_threads, -1, -1);
1659 if (completionPortThreads < min_io_threads || completionPortThreads < cpu_count)
1662 InterlockedExchange (&async_tp.max_threads, workerThreads);
1663 InterlockedExchange (&async_io_tp.max_threads, completionPortThreads);
1668 * mono_install_threadpool_thread_hooks
1669 * @start_func: the function to be called right after a new threadpool thread is created. Can be NULL.
1670 * @finish_func: the function to be called right before a thredpool thread is exiting. Can be NULL.
1671 * @user_data: argument passed to @start_func and @finish_func.
1673 * @start_fun will be called right after a threadpool thread is created and @finish_func right before a threadpool thread exits.
1674 * The calls will be made from the thread itself.
1677 mono_install_threadpool_thread_hooks (MonoThreadPoolFunc start_func, MonoThreadPoolFunc finish_func, gpointer user_data)
1679 tp_start_func = start_func;
1680 tp_finish_func = finish_func;
1681 tp_hooks_user_data = user_data;
1685 * mono_install_threadpool_item_hooks
1686 * @begin_func: the function to be called before a threadpool work item processing starts.
1687 * @end_func: the function to be called after a threadpool work item is finished.
1688 * @user_data: argument passed to @begin_func and @end_func.
1690 * The calls will be made from the thread itself and from the same AppDomain
1691 * where the work item was executed.
1695 mono_install_threadpool_item_hooks (MonoThreadPoolItemFunc begin_func, MonoThreadPoolItemFunc end_func, gpointer user_data)
1697 tp_item_begin_func = begin_func;
1698 tp_item_end_func = end_func;
1699 tp_item_user_data = user_data;