Merge pull request #5714 from alexischr/update_bockbuild
[mono.git] / mono / metadata / threadpool.c
1 /**
2  * \file
3  * Microsoft threadpool runtime support
4  *
5  * Author:
6  *      Ludovic Henry (ludovic.henry@xamarin.com)
7  *
8  * Copyright 2015 Xamarin, Inc (http://www.xamarin.com)
9  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
10  */
11
12 //
13 // Copyright (c) Microsoft. All rights reserved.
14 // Licensed under the MIT license. See LICENSE file in the project root for full license information.
15 //
16 // Files:
17 //  - src/vm/comthreadpool.cpp
18 //  - src/vm/win32threadpoolcpp
19 //  - src/vm/threadpoolrequest.cpp
20 //  - src/vm/hillclimbing.cpp
21 //
22 // Ported from C++ to C and adjusted to Mono runtime
23
24 #include <stdlib.h>
25 #define _USE_MATH_DEFINES // needed by MSVC to define math constants
26 #include <math.h>
27 #include <config.h>
28 #include <glib.h>
29
30 #include <mono/metadata/class-internals.h>
31 #include <mono/metadata/exception.h>
32 #include <mono/metadata/gc-internals.h>
33 #include <mono/metadata/object.h>
34 #include <mono/metadata/object-internals.h>
35 #include <mono/metadata/threadpool.h>
36 #include <mono/metadata/threadpool-worker.h>
37 #include <mono/metadata/threadpool-io.h>
38 #include <mono/metadata/w32event.h>
39 #include <mono/utils/atomic.h>
40 #include <mono/utils/mono-compiler.h>
41 #include <mono/utils/mono-complex.h>
42 #include <mono/utils/mono-lazy-init.h>
43 #include <mono/utils/mono-logger.h>
44 #include <mono/utils/mono-logger-internals.h>
45 #include <mono/utils/mono-proclib.h>
46 #include <mono/utils/mono-threads.h>
47 #include <mono/utils/mono-time.h>
48 #include <mono/utils/refcount.h>
49 #include <mono/utils/mono-os-wait.h>
50
51 typedef struct {
52         MonoDomain *domain;
53         /* Number of outstanding jobs */
54         gint32 outstanding_request;
55         /* Number of currently executing jobs */
56         gint32 threadpool_jobs;
57         /* Signalled when threadpool_jobs + outstanding_request is 0 */
58         /* Protected by threadpool.domains_lock */
59         MonoCoopCond cleanup_cond;
60 } ThreadPoolDomain;
61
62 typedef union {
63         struct {
64                 gint16 starting; /* starting, but not yet in worker_callback */
65                 gint16 working; /* executing worker_callback */
66         } _;
67         gint32 as_gint32;
68 } ThreadPoolCounter;
69
70 typedef struct {
71         MonoRefCount ref;
72
73         GPtrArray *domains; // ThreadPoolDomain* []
74         MonoCoopMutex domains_lock;
75
76         ThreadPoolCounter counters;
77
78         gint32 limit_io_min;
79         gint32 limit_io_max;
80 } ThreadPool;
81
82 static mono_lazy_init_t status = MONO_LAZY_INIT_STATUS_NOT_INITIALIZED;
83
84 static ThreadPool threadpool;
85
86 #define COUNTER_ATOMIC(var,block) \
87         do { \
88                 ThreadPoolCounter __old; \
89                 do { \
90                         (var) = __old = COUNTER_READ (); \
91                         { block; } \
92                         if (!(counter._.starting >= 0)) \
93                                 g_error ("%s: counter._.starting = %d, but should be >= 0", __func__, counter._.starting); \
94                         if (!(counter._.working >= 0)) \
95                                 g_error ("%s: counter._.working = %d, but should be >= 0", __func__, counter._.working); \
96                 } while (InterlockedCompareExchange (&threadpool.counters.as_gint32, (var).as_gint32, __old.as_gint32) != __old.as_gint32); \
97         } while (0)
98
99 static inline ThreadPoolCounter
100 COUNTER_READ (void)
101 {
102         ThreadPoolCounter counter;
103         counter.as_gint32 = InterlockedRead (&threadpool.counters.as_gint32);
104         return counter;
105 }
106
107 static inline void
108 domains_lock (void)
109 {
110         mono_coop_mutex_lock (&threadpool.domains_lock);
111 }
112
113 static inline void
114 domains_unlock (void)
115 {
116         mono_coop_mutex_unlock (&threadpool.domains_lock);
117 }
118
119 static void
120 destroy (gpointer unused)
121 {
122         g_ptr_array_free (threadpool.domains, TRUE);
123         mono_coop_mutex_destroy (&threadpool.domains_lock);
124 }
125
126 static void
127 worker_callback (void);
128
129 static void
130 initialize (void)
131 {
132         g_assert (sizeof (ThreadPoolCounter) == sizeof (gint32));
133
134         mono_refcount_init (&threadpool, destroy);
135
136         threadpool.domains = g_ptr_array_new ();
137         mono_coop_mutex_init (&threadpool.domains_lock);
138
139         threadpool.limit_io_min = mono_cpu_count ();
140         threadpool.limit_io_max = CLAMP (threadpool.limit_io_min * 100, MIN (threadpool.limit_io_min, 200), MAX (threadpool.limit_io_min, 200));
141
142         mono_threadpool_worker_init (worker_callback);
143 }
144
145 static void
146 cleanup (void)
147 {
148         mono_threadpool_worker_cleanup ();
149
150         mono_refcount_dec (&threadpool);
151 }
152
153 gboolean
154 mono_threadpool_enqueue_work_item (MonoDomain *domain, MonoObject *work_item, MonoError *error)
155 {
156         static MonoClass *threadpool_class = NULL;
157         static MonoMethod *unsafe_queue_custom_work_item_method = NULL;
158         MonoDomain *current_domain;
159         MonoBoolean f;
160         gpointer args [2];
161
162         error_init (error);
163         g_assert (work_item);
164
165         if (!threadpool_class)
166                 threadpool_class = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "ThreadPool");
167
168         if (!unsafe_queue_custom_work_item_method)
169                 unsafe_queue_custom_work_item_method = mono_class_get_method_from_name (threadpool_class, "UnsafeQueueCustomWorkItem", 2);
170         g_assert (unsafe_queue_custom_work_item_method);
171
172         f = FALSE;
173
174         args [0] = (gpointer) work_item;
175         args [1] = (gpointer) &f;
176
177         current_domain = mono_domain_get ();
178         if (current_domain == domain) {
179                 mono_runtime_invoke_checked (unsafe_queue_custom_work_item_method, NULL, args, error);
180                 return_val_if_nok (error, FALSE);
181         } else {
182                 mono_thread_push_appdomain_ref (domain);
183                 if (mono_domain_set (domain, FALSE)) {
184                         mono_runtime_invoke_checked (unsafe_queue_custom_work_item_method, NULL, args, error);
185                         if (!is_ok (error)) {
186                                 mono_thread_pop_appdomain_ref ();
187                                 return FALSE;
188                         }
189                         mono_domain_set (current_domain, TRUE);
190                 }
191                 mono_thread_pop_appdomain_ref ();
192         }
193         return TRUE;
194 }
195
196 /* LOCKING: domains_lock must be held. */
197 static ThreadPoolDomain *
198 tpdomain_create (MonoDomain *domain)
199 {
200         ThreadPoolDomain *tpdomain;
201
202         tpdomain = g_new0 (ThreadPoolDomain, 1);
203         tpdomain->domain = domain;
204         mono_coop_cond_init (&tpdomain->cleanup_cond);
205
206         g_ptr_array_add (threadpool.domains, tpdomain);
207
208         return tpdomain;
209 }
210
211 /* LOCKING: domains_lock must be held. */
212 static gboolean
213 tpdomain_remove (ThreadPoolDomain *tpdomain)
214 {
215         g_assert (tpdomain);
216         return g_ptr_array_remove (threadpool.domains, tpdomain);
217 }
218
219 /* LOCKING: domains_lock must be held */
220 static ThreadPoolDomain *
221 tpdomain_get (MonoDomain *domain)
222 {
223         gint i;
224
225         g_assert (domain);
226
227         for (i = 0; i < threadpool.domains->len; ++i) {
228                 ThreadPoolDomain *tpdomain;
229
230                 tpdomain = (ThreadPoolDomain *)g_ptr_array_index (threadpool.domains, i);
231                 if (tpdomain->domain == domain)
232                         return tpdomain;
233         }
234
235         return NULL;
236 }
237
238 static void
239 tpdomain_free (ThreadPoolDomain *tpdomain)
240 {
241         g_free (tpdomain);
242 }
243
244 /* LOCKING: domains_lock must be held */
245 static ThreadPoolDomain *
246 tpdomain_get_next (ThreadPoolDomain *current)
247 {
248         ThreadPoolDomain *tpdomain = NULL;
249         gint len;
250
251         len = threadpool.domains->len;
252         if (len > 0) {
253                 gint i, current_idx = -1;
254                 if (current) {
255                         for (i = 0; i < len; ++i) {
256                                 if (current == g_ptr_array_index (threadpool.domains, i)) {
257                                         current_idx = i;
258                                         break;
259                                 }
260                         }
261                 }
262                 for (i = current_idx + 1; i < len + current_idx + 1; ++i) {
263                         ThreadPoolDomain *tmp = (ThreadPoolDomain *)g_ptr_array_index (threadpool.domains, i % len);
264                         if (tmp->outstanding_request > 0) {
265                                 tpdomain = tmp;
266                                 break;
267                         }
268                 }
269         }
270
271         return tpdomain;
272 }
273
274 static MonoObject*
275 try_invoke_perform_wait_callback (MonoObject** exc, MonoError *error)
276 {
277         HANDLE_FUNCTION_ENTER ();
278         error_init (error);
279         MonoObject *res = mono_runtime_try_invoke (mono_defaults.threadpool_perform_wait_callback_method, NULL, NULL, exc, error);
280         HANDLE_FUNCTION_RETURN_VAL (res);
281 }
282
283 static void
284 worker_callback (void)
285 {
286         MonoError error;
287         ThreadPoolDomain *tpdomain, *previous_tpdomain;
288         ThreadPoolCounter counter;
289         MonoInternalThread *thread;
290
291         if (!mono_refcount_tryinc (&threadpool))
292                 return;
293
294         thread = mono_thread_internal_current ();
295
296         COUNTER_ATOMIC (counter, {
297                 if (!(counter._.working < 32767 /* G_MAXINT16 */))
298                         g_error ("%s: counter._.working = %d, but should be < 32767", __func__, counter._.working);
299
300                 counter._.starting --;
301                 counter._.working ++;
302         });
303
304         if (mono_runtime_is_shutting_down ()) {
305                 COUNTER_ATOMIC (counter, {
306                         counter._.working --;
307                 });
308
309                 mono_refcount_dec (&threadpool);
310                 return;
311         }
312
313         /*
314          * This is needed so there is always an lmf frame in the runtime invoke call below,
315          * so ThreadAbortExceptions are caught even if the thread is in native code.
316          */
317         mono_defaults.threadpool_perform_wait_callback_method->save_lmf = TRUE;
318
319         domains_lock ();
320
321         previous_tpdomain = NULL;
322
323         while (!mono_runtime_is_shutting_down ()) {
324                 gboolean retire = FALSE;
325
326                 if (thread->state & (ThreadState_AbortRequested | ThreadState_SuspendRequested)) {
327                         domains_unlock ();
328                         if (mono_thread_interruption_checkpoint ()) {
329                                 domains_lock ();
330                                 continue;
331                         }
332                         domains_lock ();
333                 }
334
335                 tpdomain = tpdomain_get_next (previous_tpdomain);
336                 if (!tpdomain)
337                         break;
338
339                 tpdomain->outstanding_request --;
340                 g_assert (tpdomain->outstanding_request >= 0);
341
342                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] worker running in domain %p (outstanding requests %d)",
343                         GUINT_TO_POINTER (MONO_NATIVE_THREAD_ID_TO_UINT (mono_native_thread_id_get ())), tpdomain->domain, tpdomain->outstanding_request);
344
345                 g_assert (tpdomain->threadpool_jobs >= 0);
346                 tpdomain->threadpool_jobs ++;
347
348                 domains_unlock ();
349
350                 MonoString *thread_name = mono_string_new_checked (mono_get_root_domain (), "Threadpool worker", &error);
351                 mono_error_assert_ok (&error);
352                 mono_thread_set_name_internal (thread, thread_name, FALSE, TRUE, &error);
353                 mono_error_assert_ok (&error);
354
355                 mono_thread_clr_state (thread, (MonoThreadState)~ThreadState_Background);
356                 if (!mono_thread_test_state (thread , ThreadState_Background))
357                         ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
358
359                 mono_thread_push_appdomain_ref (tpdomain->domain);
360                 if (mono_domain_set (tpdomain->domain, FALSE)) {
361                         MonoObject *exc = NULL, *res;
362
363                         res = try_invoke_perform_wait_callback (&exc, &error);
364                         if (exc || !mono_error_ok(&error)) {
365                                 if (exc == NULL)
366                                         exc = (MonoObject *) mono_error_convert_to_exception (&error);
367                                 else
368                                         mono_error_cleanup (&error);
369                                 mono_thread_internal_unhandled_exception (exc);
370                         } else if (res && *(MonoBoolean*) mono_object_unbox (res) == FALSE) {
371                                 retire = TRUE;
372                         }
373
374                         mono_domain_set (mono_get_root_domain (), TRUE);
375                 }
376                 mono_thread_pop_appdomain_ref ();
377
378                 domains_lock ();
379
380                 tpdomain->threadpool_jobs --;
381                 g_assert (tpdomain->threadpool_jobs >= 0);
382
383                 if (tpdomain->outstanding_request + tpdomain->threadpool_jobs == 0 && mono_domain_is_unloading (tpdomain->domain)) {
384                         gboolean removed;
385
386                         removed = tpdomain_remove (tpdomain);
387                         g_assert (removed);
388
389                         mono_coop_cond_signal (&tpdomain->cleanup_cond);
390                         tpdomain = NULL;
391                 }
392
393                 if (retire)
394                         break;
395
396                 previous_tpdomain = tpdomain;
397         }
398
399         domains_unlock ();
400
401         COUNTER_ATOMIC (counter, {
402                 counter._.working --;
403         });
404
405         mono_refcount_dec (&threadpool);
406 }
407
408 void
409 mono_threadpool_cleanup (void)
410 {
411 #ifndef DISABLE_SOCKETS
412         mono_threadpool_io_cleanup ();
413 #endif
414         mono_lazy_cleanup (&status, cleanup);
415 }
416
417 MonoAsyncResult *
418 mono_threadpool_begin_invoke (MonoDomain *domain, MonoObject *target, MonoMethod *method, gpointer *params, MonoError *error)
419 {
420         static MonoClass *async_call_klass = NULL;
421         MonoMethodMessage *message;
422         MonoAsyncResult *async_result;
423         MonoAsyncCall *async_call;
424         MonoDelegate *async_callback = NULL;
425         MonoObject *state = NULL;
426
427         if (!async_call_klass)
428                 async_call_klass = mono_class_load_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
429
430         error_init (error);
431
432         message = mono_method_call_message_new (method, params, mono_get_delegate_invoke (method->klass), (params != NULL) ? (&async_callback) : NULL, (params != NULL) ? (&state) : NULL, error);
433         return_val_if_nok (error, NULL);
434
435         async_call = (MonoAsyncCall*) mono_object_new_checked (domain, async_call_klass, error);
436         return_val_if_nok (error, NULL);
437
438         MONO_OBJECT_SETREF (async_call, msg, message);
439         MONO_OBJECT_SETREF (async_call, state, state);
440
441         if (async_callback) {
442                 MONO_OBJECT_SETREF (async_call, cb_method, mono_get_delegate_invoke (((MonoObject*) async_callback)->vtable->klass));
443                 MONO_OBJECT_SETREF (async_call, cb_target, async_callback);
444         }
445
446         async_result = mono_async_result_new (domain, NULL, async_call->state, NULL, (MonoObject*) async_call, error);
447         return_val_if_nok (error, NULL);
448         MONO_OBJECT_SETREF (async_result, async_delegate, target);
449
450         mono_threadpool_enqueue_work_item (domain, (MonoObject*) async_result, error);
451         return_val_if_nok (error, NULL);
452
453         return async_result;
454 }
455
456 MonoObject *
457 mono_threadpool_end_invoke (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc, MonoError *error)
458 {
459         MonoAsyncCall *ac;
460
461         error_init (error);
462         g_assert (exc);
463         g_assert (out_args);
464
465         *exc = NULL;
466         *out_args = NULL;
467
468         /* check if already finished */
469         mono_monitor_enter ((MonoObject*) ares);
470
471         if (ares->endinvoke_called) {
472                 mono_error_set_invalid_operation(error, "Delegate EndInvoke method called more than once");
473                 mono_monitor_exit ((MonoObject*) ares);
474                 return NULL;
475         }
476
477         ares->endinvoke_called = 1;
478
479         /* wait until we are really finished */
480         if (ares->completed) {
481                 mono_monitor_exit ((MonoObject *) ares);
482         } else {
483                 gpointer wait_event;
484                 if (ares->handle) {
485                         wait_event = mono_wait_handle_get_handle ((MonoWaitHandle*) ares->handle);
486                 } else {
487                         wait_event = mono_w32event_create (TRUE, FALSE);
488                         g_assert(wait_event);
489                         MonoWaitHandle *wait_handle = mono_wait_handle_new (mono_object_domain (ares), wait_event, error);
490                         if (!is_ok (error)) {
491                                 mono_w32event_close (wait_event);
492                                 return NULL;
493                         }
494                         MONO_OBJECT_SETREF (ares, handle, (MonoObject*) wait_handle);
495                 }
496                 mono_monitor_exit ((MonoObject*) ares);
497                 MONO_ENTER_GC_SAFE;
498 #ifdef HOST_WIN32
499                 mono_win32_wait_for_single_object_ex (wait_event, INFINITE, TRUE);
500 #else
501                 mono_w32handle_wait_one (wait_event, MONO_INFINITE_WAIT, TRUE);
502 #endif
503                 MONO_EXIT_GC_SAFE;
504         }
505
506         ac = (MonoAsyncCall*) ares->object_data;
507         g_assert (ac);
508
509         *exc = ac->msg->exc; /* FIXME: GC add write barrier */
510         *out_args = ac->out_args;
511         return ac->res;
512 }
513
514 gboolean
515 mono_threadpool_remove_domain_jobs (MonoDomain *domain, int timeout)
516 {
517         gint64 end;
518         ThreadPoolDomain *tpdomain;
519         gboolean ret;
520
521         g_assert (domain);
522         g_assert (timeout >= -1);
523
524         g_assert (mono_domain_is_unloading (domain));
525
526         if (timeout != -1)
527                 end = mono_msec_ticks () + timeout;
528
529 #ifndef DISABLE_SOCKETS
530         mono_threadpool_io_remove_domain_jobs (domain);
531         if (timeout != -1) {
532                 if (mono_msec_ticks () > end)
533                         return FALSE;
534         }
535 #endif
536
537         /*
538          * Wait for all threads which execute jobs in the domain to exit.
539          * The is_unloading () check in worker_request () ensures that
540          * no new jobs are added after we enter the lock below.
541          */
542
543         if (!mono_lazy_is_initialized (&status))
544                 return TRUE;
545
546         mono_refcount_inc (&threadpool);
547
548         domains_lock ();
549
550         tpdomain = tpdomain_get (domain);
551         if (!tpdomain) {
552                 domains_unlock ();
553                 mono_refcount_dec (&threadpool);
554                 return TRUE;
555         }
556
557         ret = TRUE;
558
559         while (tpdomain->outstanding_request + tpdomain->threadpool_jobs > 0) {
560                 if (timeout == -1) {
561                         mono_coop_cond_wait (&tpdomain->cleanup_cond, &threadpool.domains_lock);
562                 } else {
563                         gint64 now;
564                         gint res;
565
566                         now = mono_msec_ticks();
567                         if (now > end) {
568                                 ret = FALSE;
569                                 break;
570                         }
571
572                         res = mono_coop_cond_timedwait (&tpdomain->cleanup_cond, &threadpool.domains_lock, end - now);
573                         if (res != 0) {
574                                 ret = FALSE;
575                                 break;
576                         }
577                 }
578         }
579
580         /* Remove from the list the worker threads look at */
581         tpdomain_remove (tpdomain);
582
583         domains_unlock ();
584
585         mono_coop_cond_destroy (&tpdomain->cleanup_cond);
586         tpdomain_free (tpdomain);
587
588         mono_refcount_dec (&threadpool);
589
590         return ret;
591 }
592
593 void
594 mono_threadpool_suspend (void)
595 {
596         if (mono_lazy_is_initialized (&status))
597                 mono_threadpool_worker_set_suspended (TRUE);
598 }
599
600 void
601 mono_threadpool_resume (void)
602 {
603         if (mono_lazy_is_initialized (&status))
604                 mono_threadpool_worker_set_suspended (FALSE);
605 }
606
607 void
608 ves_icall_System_Threading_ThreadPool_GetAvailableThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
609 {
610         ThreadPoolCounter counter;
611
612         if (!worker_threads || !completion_port_threads)
613                 return;
614
615         if (!mono_lazy_initialize (&status, initialize) || !mono_refcount_tryinc (&threadpool)) {
616                 *worker_threads = 0;
617                 *completion_port_threads = 0;
618                 return;
619         }
620
621         counter = COUNTER_READ ();
622
623         *worker_threads = MAX (0, mono_threadpool_worker_get_max () - counter._.working);
624         *completion_port_threads = threadpool.limit_io_max;
625
626         mono_refcount_dec (&threadpool);
627 }
628
629 void
630 ves_icall_System_Threading_ThreadPool_GetMinThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
631 {
632         if (!worker_threads || !completion_port_threads)
633                 return;
634
635         if (!mono_lazy_initialize (&status, initialize) || !mono_refcount_tryinc (&threadpool)) {
636                 *worker_threads = 0;
637                 *completion_port_threads = 0;
638                 return;
639         }
640
641         *worker_threads = mono_threadpool_worker_get_min ();
642         *completion_port_threads = threadpool.limit_io_min;
643
644         mono_refcount_dec (&threadpool);
645 }
646
647 void
648 ves_icall_System_Threading_ThreadPool_GetMaxThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
649 {
650         if (!worker_threads || !completion_port_threads)
651                 return;
652
653         if (!mono_lazy_initialize (&status, initialize) || !mono_refcount_tryinc (&threadpool)) {
654                 *worker_threads = 0;
655                 *completion_port_threads = 0;
656                 return;
657         }
658
659         *worker_threads = mono_threadpool_worker_get_max ();
660         *completion_port_threads = threadpool.limit_io_max;
661
662         mono_refcount_dec (&threadpool);
663 }
664
665 MonoBoolean
666 ves_icall_System_Threading_ThreadPool_SetMinThreadsNative (gint32 worker_threads, gint32 completion_port_threads)
667 {
668         if (completion_port_threads <= 0 || completion_port_threads > threadpool.limit_io_max)
669                 return FALSE;
670
671         if (!mono_lazy_initialize (&status, initialize) || !mono_refcount_tryinc (&threadpool))
672                 return FALSE;
673
674         if (!mono_threadpool_worker_set_min (worker_threads)) {
675                 mono_refcount_dec (&threadpool);
676                 return FALSE;
677         }
678
679         threadpool.limit_io_min = completion_port_threads;
680
681         mono_refcount_dec (&threadpool);
682         return TRUE;
683 }
684
685 MonoBoolean
686 ves_icall_System_Threading_ThreadPool_SetMaxThreadsNative (gint32 worker_threads, gint32 completion_port_threads)
687 {
688         gint cpu_count = mono_cpu_count ();
689
690         if (completion_port_threads < threadpool.limit_io_min || completion_port_threads < cpu_count)
691                 return FALSE;
692
693         if (!mono_lazy_initialize (&status, initialize) || !mono_refcount_tryinc (&threadpool))
694                 return FALSE;
695
696         if (!mono_threadpool_worker_set_max (worker_threads)) {
697                 mono_refcount_dec (&threadpool);
698                 return FALSE;
699         }
700
701         threadpool.limit_io_max = completion_port_threads;
702
703         mono_refcount_dec (&threadpool);
704         return TRUE;
705 }
706
707 void
708 ves_icall_System_Threading_ThreadPool_InitializeVMTp (MonoBoolean *enable_worker_tracking)
709 {
710         if (enable_worker_tracking) {
711                 // TODO implement some kind of switch to have the possibily to use it
712                 *enable_worker_tracking = FALSE;
713         }
714
715         mono_lazy_initialize (&status, initialize);
716 }
717
718 MonoBoolean
719 ves_icall_System_Threading_ThreadPool_NotifyWorkItemComplete (void)
720 {
721         if (mono_domain_is_unloading (mono_domain_get ()) || mono_runtime_is_shutting_down ())
722                 return FALSE;
723
724         return mono_threadpool_worker_notify_completed ();
725 }
726
727 void
728 ves_icall_System_Threading_ThreadPool_NotifyWorkItemProgressNative (void)
729 {
730         mono_threadpool_worker_notify_completed ();
731 }
732
733 void
734 ves_icall_System_Threading_ThreadPool_ReportThreadStatus (MonoBoolean is_working)
735 {
736         // TODO
737         MonoError error;
738         mono_error_set_not_implemented (&error, "");
739         mono_error_set_pending_exception (&error);
740 }
741
742 MonoBoolean
743 ves_icall_System_Threading_ThreadPool_RequestWorkerThread (void)
744 {
745         MonoDomain *domain;
746         ThreadPoolDomain *tpdomain;
747         ThreadPoolCounter counter;
748
749         domain = mono_domain_get ();
750         if (mono_domain_is_unloading (domain))
751                 return FALSE;
752
753         if (!mono_lazy_initialize (&status, initialize) || !mono_refcount_tryinc (&threadpool)) {
754                 /* threadpool has been destroyed, we are shutting down */
755                 return FALSE;
756         }
757
758         domains_lock ();
759
760         tpdomain = tpdomain_get (domain);
761         if (!tpdomain) {
762                 /* synchronize with mono_threadpool_remove_domain_jobs */
763                 if (mono_domain_is_unloading (domain)) {
764                         domains_unlock ();
765                         mono_refcount_dec (&threadpool);
766                         return FALSE;
767                 }
768
769                 tpdomain = tpdomain_create (domain);
770         }
771
772         g_assert (tpdomain);
773
774         tpdomain->outstanding_request ++;
775         g_assert (tpdomain->outstanding_request >= 1);
776
777         domains_unlock ();
778
779         COUNTER_ATOMIC (counter, {
780                 if (counter._.starting == 16) {
781                         mono_refcount_dec (&threadpool);
782                         return TRUE;
783                 }
784
785                 counter._.starting ++;
786         });
787
788         mono_threadpool_worker_request ();
789
790         mono_refcount_dec (&threadpool);
791         return TRUE;
792 }
793
794 MonoBoolean G_GNUC_UNUSED
795 ves_icall_System_Threading_ThreadPool_PostQueuedCompletionStatus (MonoNativeOverlapped *native_overlapped)
796 {
797         /* This copy the behavior of the current Mono implementation */
798         MonoError error;
799         mono_error_set_not_implemented (&error, "");
800         mono_error_set_pending_exception (&error);
801         return FALSE;
802 }
803
804 MonoBoolean G_GNUC_UNUSED
805 ves_icall_System_Threading_ThreadPool_BindIOCompletionCallbackNative (gpointer file_handle)
806 {
807         /* This copy the behavior of the current Mono implementation */
808         return TRUE;
809 }
810
811 MonoBoolean G_GNUC_UNUSED
812 ves_icall_System_Threading_ThreadPool_IsThreadPoolHosted (void)
813 {
814         return FALSE;
815 }