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