/
threadpool.c
1756 lines (1514 loc) · 45.6 KB
/
threadpool.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* threadpool.c: global thread pool
*
* Authors:
* Dietmar Maurer (dietmar@ximian.com)
* Gonzalo Paniagua Javier (gonzalo@ximian.com)
*
* Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
* Copyright 2004-2010 Novell, Inc (http://www.novell.com)
* Copyright 2001 Xamarin Inc (http://www.xamarin.com)
*/
#include <config.h>
#include <glib.h>
#include <mono/metadata/profiler-private.h>
#include <mono/metadata/threads.h>
#include <mono/metadata/threads-types.h>
#include <mono/metadata/threadpool-internals.h>
#include <mono/metadata/exception.h>
#include <mono/metadata/environment.h>
#include <mono/metadata/mono-config.h>
#include <mono/metadata/mono-mlist.h>
#include <mono/metadata/mono-perfcounters.h>
#include <mono/metadata/socket-io.h>
#include <mono/metadata/mono-cq.h>
#include <mono/metadata/mono-wsq.h>
#include <mono/metadata/mono-ptr-array.h>
#include <mono/io-layer/io-layer.h>
#include <mono/utils/mono-time.h>
#include <mono/utils/mono-proclib.h>
#include <mono/utils/mono-semaphore.h>
#include <mono/utils/atomic.h>
#include <errno.h>
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#include <sys/types.h>
#include <fcntl.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <string.h>
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#include <mono/utils/mono-poll.h>
#ifdef HAVE_EPOLL
#include <sys/epoll.h>
#endif
#ifdef HAVE_KQUEUE
#include <sys/event.h>
#endif
#ifndef DISABLE_SOCKETS
#include "mono/io-layer/socket-wrappers.h"
#endif
#include "threadpool.h"
#define THREAD_WANTS_A_BREAK(t) ((t->state & (ThreadState_StopRequested | \
ThreadState_SuspendRequested)) != 0)
#define SPIN_TRYLOCK(i) (InterlockedCompareExchange (&(i), 1, 0) == 0)
#define SPIN_LOCK(i) do { \
if (SPIN_TRYLOCK (i)) \
break; \
} while (1)
#define SPIN_UNLOCK(i) i = 0
#define SMALL_STACK (128 * (sizeof (gpointer) / 4) * 1024)
/* DEBUG: prints tp data every 2s */
#undef DEBUG
/* mono_thread_pool_init called */
static volatile int tp_inited;
enum {
POLL_BACKEND,
EPOLL_BACKEND,
KQUEUE_BACKEND
};
typedef struct {
CRITICAL_SECTION io_lock; /* access to sock_to_state */
int inited; // 0 -> not initialized , 1->initializing, 2->initialized, 3->cleaned up
MonoGHashTable *sock_to_state;
gint event_system;
gpointer event_data;
void (*modify) (gpointer p, int fd, int operation, int events, gboolean is_new);
void (*wait) (gpointer sock_data);
void (*shutdown) (gpointer event_data);
} SocketIOData;
static SocketIOData socket_io_data;
/* Keep in sync with the System.MonoAsyncCall class which provides GC tracking */
typedef struct {
MonoObject object;
MonoMethodMessage *msg;
MonoMethod *cb_method;
MonoDelegate *cb_target;
MonoObject *state;
MonoObject *res;
MonoArray *out_args;
} ASyncCall;
typedef struct {
MonoSemType lock;
MonoCQ *queue; /* GC root */
MonoSemType new_job;
volatile gint waiting; /* threads waiting for a work item */
/**/
volatile gint pool_status; /* 0 -> not initialized, 1 -> initialized, 2 -> cleaning up */
/* min, max, n and busy -> Interlocked */
volatile gint min_threads;
volatile gint max_threads;
volatile gint nthreads;
volatile gint busy_threads;
void (*async_invoke) (gpointer data);
void *pc_nitems; /* Performance counter for total number of items in added */
void *pc_nthreads; /* Performance counter for total number of active threads */
/**/
volatile gint destroy_thread;
volatile gint ignore_times; /* Used when there's a thread being created or destroyed */
volatile gint sp_lock; /* spin lock used to protect ignore_times */
volatile gint64 last_check;
volatile gint64 time_sum;
volatile gint n_sum;
gint64 averages [2];
gboolean is_io;
} ThreadPool;
static ThreadPool async_tp;
static ThreadPool async_io_tp;
static void async_invoke_thread (gpointer data);
static MonoObject *mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares);
static void threadpool_free_queue (ThreadPool *tp);
static void threadpool_append_job (ThreadPool *tp, MonoObject *ar);
static void threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs);
static void threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer));
static void threadpool_start_idle_threads (ThreadPool *tp);
static void threadpool_kill_idle_threads (ThreadPool *tp);
static gboolean threadpool_start_thread (ThreadPool *tp);
static void monitor_thread (gpointer data);
static void socket_io_cleanup (SocketIOData *data);
static MonoObject *get_io_event (MonoMList **list, gint event);
static int get_events_from_list (MonoMList *list);
static int get_event_from_state (MonoSocketAsyncResult *state);
static void check_for_interruption_critical (void);
static MonoClass *async_call_klass;
static MonoClass *socket_async_call_klass;
static MonoClass *process_async_call_klass;
static GPtrArray *wsqs;
CRITICAL_SECTION wsqs_lock;
static gboolean suspended;
/* Hooks */
static MonoThreadPoolFunc tp_start_func;
static MonoThreadPoolFunc tp_finish_func;
static gpointer tp_hooks_user_data;
static MonoThreadPoolItemFunc tp_item_begin_func;
static MonoThreadPoolItemFunc tp_item_end_func;
static gpointer tp_item_user_data;
enum {
AIO_OP_FIRST,
AIO_OP_ACCEPT = 0,
AIO_OP_CONNECT,
AIO_OP_RECEIVE,
AIO_OP_RECEIVEFROM,
AIO_OP_SEND,
AIO_OP_SENDTO,
AIO_OP_RECV_JUST_CALLBACK,
AIO_OP_SEND_JUST_CALLBACK,
AIO_OP_READPIPE,
AIO_OP_CONSOLE2,
AIO_OP_DISCONNECT,
AIO_OP_ACCEPTRECEIVE,
AIO_OP_RECEIVE_BUFFERS,
AIO_OP_SEND_BUFFERS,
AIO_OP_LAST
};
#include <mono/metadata/tpool-poll.c>
#ifdef HAVE_EPOLL
#include <mono/metadata/tpool-epoll.c>
#elif defined(USE_KQUEUE_FOR_THREADPOOL)
#include <mono/metadata/tpool-kqueue.c>
#endif
/*
* Functions to check whenever a class is given system class. We need to cache things in MonoDomain since some of the
* assemblies can be unloaded.
*/
static gboolean
is_system_type (MonoDomain *domain, MonoClass *klass)
{
if (domain->system_image == NULL)
domain->system_image = mono_image_loaded ("System");
return klass->image == domain->system_image;
}
static gboolean
is_corlib_type (MonoDomain *domain, MonoClass *klass)
{
return klass->image == mono_defaults.corlib;
}
/*
* Note that we call it is_socket_type() where 'socket' refers to the image
* that contains the System.Net.Sockets.Socket type.
*/
static gboolean
is_socket_type (MonoDomain *domain, MonoClass *klass)
{
return is_system_type (domain, klass);
}
#define check_type_cached(domain, ASSEMBLY, _class, _namespace, _name, loc) do { \
if (*loc) \
return *loc == _class; \
if (is_##ASSEMBLY##_type (domain, _class) && !strcmp (_name, _class->name) && !strcmp (_namespace, _class->name_space)) { \
*loc = _class; \
return TRUE; \
} \
return FALSE; \
} while (0) \
#define check_corlib_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, corlib, _class, _namespace, _name, loc)
#define check_socket_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, socket, _class, _namespace, _name, loc)
#define check_system_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, system, _class, _namespace, _name, loc)
static gboolean
is_corlib_asyncresult (MonoDomain *domain, MonoClass *klass)
{
check_corlib_type_cached (domain, klass, "System.Runtime.Remoting.Messaging", "AsyncResult", &domain->corlib_asyncresult_class);
}
static gboolean
is_socket (MonoDomain *domain, MonoClass *klass)
{
check_socket_type_cached (domain, klass, "System.Net.Sockets", "Socket", &domain->socket_class);
}
static gboolean
is_socketasyncresult (MonoDomain *domain, MonoClass *klass)
{
return (klass->nested_in &&
is_socket (domain, klass->nested_in) &&
!strcmp (klass->name, "SocketAsyncResult"));
}
static gboolean
is_socketasynccall (MonoDomain *domain, MonoClass *klass)
{
return (klass->nested_in &&
is_socket (domain, klass->nested_in) &&
!strcmp (klass->name, "SocketAsyncCall"));
}
static gboolean
is_appdomainunloaded_exception (MonoDomain *domain, MonoClass *klass)
{
check_corlib_type_cached (domain, klass, "System", "AppDomainUnloadedException", &domain->ad_unloaded_ex_class);
}
static gboolean
is_sd_process (MonoDomain *domain, MonoClass *klass)
{
check_system_type_cached (domain, klass, "System.Diagnostics", "Process", &domain->process_class);
}
static gboolean
is_sdp_asyncreadhandler (MonoDomain *domain, MonoClass *klass)
{
return (klass->nested_in &&
is_sd_process (domain, klass->nested_in) &&
!strcmp (klass->name, "AsyncReadHandler"));
}
#ifdef DISABLE_SOCKETS
#define socket_io_cleanup(x)
static int
get_event_from_state (MonoSocketAsyncResult *state)
{
g_assert_not_reached ();
return -1;
}
static int
get_events_from_list (MonoMList *list)
{
return 0;
}
#else
static void
socket_io_cleanup (SocketIOData *data)
{
EnterCriticalSection (&data->io_lock);
if (data->inited != 2) {
LeaveCriticalSection (&data->io_lock);
return;
}
data->inited = 3;
data->shutdown (data->event_data);
LeaveCriticalSection (&data->io_lock);
}
static int
get_event_from_state (MonoSocketAsyncResult *state)
{
switch (state->operation) {
case AIO_OP_ACCEPT:
case AIO_OP_RECEIVE:
case AIO_OP_RECV_JUST_CALLBACK:
case AIO_OP_RECEIVEFROM:
case AIO_OP_READPIPE:
case AIO_OP_ACCEPTRECEIVE:
case AIO_OP_RECEIVE_BUFFERS:
return MONO_POLLIN;
case AIO_OP_SEND:
case AIO_OP_SEND_JUST_CALLBACK:
case AIO_OP_SENDTO:
case AIO_OP_CONNECT:
case AIO_OP_SEND_BUFFERS:
case AIO_OP_DISCONNECT:
return MONO_POLLOUT;
default: /* Should never happen */
g_message ("get_event_from_state: unknown value in switch!!!");
return 0;
}
}
static int
get_events_from_list (MonoMList *list)
{
MonoSocketAsyncResult *state;
int events = 0;
while (list && (state = (MonoSocketAsyncResult *)mono_mlist_get_data (list))) {
events |= get_event_from_state (state);
list = mono_mlist_next (list);
}
return events;
}
#define ICALL_RECV(x) ves_icall_System_Net_Sockets_Socket_Receive_internal (\
(SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
x->socket_flags, &x->error);
#define ICALL_SEND(x) ves_icall_System_Net_Sockets_Socket_Send_internal (\
(SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
x->socket_flags, &x->error);
#endif /* !DISABLE_SOCKETS */
static void
threadpool_jobs_inc (MonoObject *obj)
{
if (obj)
InterlockedIncrement (&obj->vtable->domain->threadpool_jobs);
}
static gboolean
threadpool_jobs_dec (MonoObject *obj)
{
MonoDomain *domain;
int remaining_jobs;
if (obj == NULL)
return FALSE;
domain = obj->vtable->domain;
remaining_jobs = InterlockedDecrement (&domain->threadpool_jobs);
if (remaining_jobs == 0 && domain->cleanup_semaphore) {
ReleaseSemaphore (domain->cleanup_semaphore, 1, NULL);
return TRUE;
}
return FALSE;
}
static MonoObject *
get_io_event (MonoMList **list, gint event)
{
MonoObject *state;
MonoMList *current;
MonoMList *prev;
current = *list;
prev = NULL;
state = NULL;
while (current) {
state = mono_mlist_get_data (current);
if (get_event_from_state ((MonoSocketAsyncResult *) state) == event)
break;
state = NULL;
prev = current;
current = mono_mlist_next (current);
}
if (current) {
if (prev) {
mono_mlist_set_next (prev, mono_mlist_next (current));
} else {
*list = mono_mlist_next (*list);
}
}
return state;
}
/*
* select/poll wake up when a socket is closed, but epoll just removes
* the socket from its internal list without notification.
*/
void
mono_thread_pool_remove_socket (int sock)
{
MonoMList *list;
MonoSocketAsyncResult *state;
MonoObject *ares;
if (socket_io_data.inited == 0)
return;
EnterCriticalSection (&socket_io_data.io_lock);
if (socket_io_data.sock_to_state == NULL) {
LeaveCriticalSection (&socket_io_data.io_lock);
return;
}
list = mono_g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
if (list)
mono_g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
LeaveCriticalSection (&socket_io_data.io_lock);
while (list) {
state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
if (state->operation == AIO_OP_RECEIVE)
state->operation = AIO_OP_RECV_JUST_CALLBACK;
else if (state->operation == AIO_OP_SEND)
state->operation = AIO_OP_SEND_JUST_CALLBACK;
ares = get_io_event (&list, MONO_POLLIN);
threadpool_append_job (&async_io_tp, ares);
if (list) {
ares = get_io_event (&list, MONO_POLLOUT);
threadpool_append_job (&async_io_tp, ares);
}
}
}
static void
init_event_system (SocketIOData *data)
{
#ifdef HAVE_EPOLL
if (data->event_system == EPOLL_BACKEND) {
data->event_data = tp_epoll_init (data);
if (data->event_data == NULL) {
if (g_getenv ("MONO_DEBUG"))
g_message ("Falling back to poll()");
data->event_system = POLL_BACKEND;
}
}
#elif defined(USE_KQUEUE_FOR_THREADPOOL)
if (data->event_system == KQUEUE_BACKEND)
data->event_data = tp_kqueue_init (data);
#endif
if (data->event_system == POLL_BACKEND)
data->event_data = tp_poll_init (data);
}
static void
socket_io_init (SocketIOData *data)
{
int inited;
if (data->inited >= 2) // 2 -> initialized, 3-> cleaned up
return;
inited = InterlockedCompareExchange (&data->inited, 1, 0);
if (inited >= 1) {
while (TRUE) {
if (data->inited >= 2)
return;
SleepEx (1, FALSE);
}
}
EnterCriticalSection (&data->io_lock);
data->sock_to_state = mono_g_hash_table_new_type (g_direct_hash, g_direct_equal, MONO_HASH_VALUE_GC);
#ifdef HAVE_EPOLL
data->event_system = EPOLL_BACKEND;
#elif defined(USE_KQUEUE_FOR_THREADPOOL)
data->event_system = KQUEUE_BACKEND;
#else
data->event_system = POLL_BACKEND;
#endif
if (g_getenv ("MONO_DISABLE_AIO") != NULL)
data->event_system = POLL_BACKEND;
init_event_system (data);
mono_thread_create_internal (mono_get_root_domain (), data->wait, data, TRUE, SMALL_STACK);
LeaveCriticalSection (&data->io_lock);
data->inited = 2;
threadpool_start_thread (&async_io_tp);
}
static void
socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
{
MonoMList *list;
SocketIOData *data = &socket_io_data;
int fd;
gboolean is_new;
int ievt;
socket_io_init (&socket_io_data);
if (mono_runtime_is_shutting_down () || data->inited == 3 || data->sock_to_state == NULL)
return;
if (async_tp.pool_status == 2)
return;
MONO_OBJECT_SETREF (state, ares, ares);
fd = GPOINTER_TO_INT (state->handle);
EnterCriticalSection (&data->io_lock);
if (data->sock_to_state == NULL) {
LeaveCriticalSection (&data->io_lock);
return;
}
list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
if (list == NULL) {
list = mono_mlist_alloc ((MonoObject*)state);
is_new = TRUE;
} else {
list = mono_mlist_append (list, (MonoObject*)state);
is_new = FALSE;
}
mono_g_hash_table_replace (data->sock_to_state, state->handle, list);
ievt = get_events_from_list (list);
/* The modify function leaves the io_lock critical section. */
data->modify (data, fd, state->operation, ievt, is_new);
}
#ifndef DISABLE_SOCKETS
static gboolean
socket_io_filter (MonoObject *target, MonoObject *state)
{
gint op;
MonoSocketAsyncResult *sock_res;
MonoClass *klass;
MonoDomain *domain;
if (target == NULL || state == NULL)
return FALSE;
domain = target->vtable->domain;
klass = target->vtable->klass;
if (socket_async_call_klass == NULL && is_socketasynccall (domain, klass))
socket_async_call_klass = klass;
if (process_async_call_klass == NULL && is_sdp_asyncreadhandler (domain, klass))
process_async_call_klass = klass;
if (klass != socket_async_call_klass && klass != process_async_call_klass)
return FALSE;
sock_res = (MonoSocketAsyncResult *) state;
op = sock_res->operation;
if (op < AIO_OP_FIRST || op >= AIO_OP_LAST)
return FALSE;
return TRUE;
}
#endif /* !DISABLE_SOCKETS */
/* Returns the exception thrown when invoking, if any */
static MonoObject *
mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares)
{
ASyncCall *ac = (ASyncCall *)ares->object_data;
MonoObject *res, *exc = NULL;
MonoArray *out_args = NULL;
HANDLE wait_event = NULL;
MonoInternalThread *thread = mono_thread_internal_current ();
if (ares->execution_context) {
/* use captured ExecutionContext (if available) */
MONO_OBJECT_SETREF (ares, original_context, mono_thread_get_execution_context ());
mono_thread_set_execution_context (ares->execution_context);
} else {
ares->original_context = NULL;
}
if (ac == NULL) {
/* Fast path from ThreadPool.*QueueUserWorkItem */
void *pa = ares->async_state;
/* The debugger needs this */
thread->async_invoke_method = ((MonoDelegate*)ares->async_delegate)->method;
res = mono_runtime_delegate_invoke (ares->async_delegate, &pa, &exc);
thread->async_invoke_method = NULL;
} else {
MonoObject *cb_exc = NULL;
ac->msg->exc = NULL;
res = mono_message_invoke (ares->async_delegate, ac->msg, &exc, &out_args);
MONO_OBJECT_SETREF (ac, res, res);
MONO_OBJECT_SETREF (ac, msg->exc, exc);
MONO_OBJECT_SETREF (ac, out_args, out_args);
mono_monitor_enter ((MonoObject *) ares);
ares->completed = 1;
if (ares->handle != NULL)
wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
mono_monitor_exit ((MonoObject *) ares);
/* notify listeners */
if (wait_event != NULL)
SetEvent (wait_event);
/* call async callback if cb_method != null*/
if (ac != NULL && ac->cb_method) {
void *pa = &ares;
cb_exc = NULL;
thread->async_invoke_method = ac->cb_method;
mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &cb_exc);
thread->async_invoke_method = NULL;
exc = cb_exc;
} else {
exc = NULL;
}
}
/* restore original thread execution context if flow isn't suppressed, i.e. non null */
if (ares->original_context) {
mono_thread_set_execution_context (ares->original_context);
ares->original_context = NULL;
}
return exc;
}
static void
threadpool_start_idle_threads (ThreadPool *tp)
{
int n;
guint32 stack_size;
stack_size = (!tp->is_io) ? 0 : SMALL_STACK;
do {
while (1) {
n = tp->nthreads;
if (n >= tp->min_threads)
return;
if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n)
break;
}
#ifndef DISABLE_PERFCOUNTERS
mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
#endif
mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE, stack_size);
SleepEx (100, TRUE);
} while (1);
}
static void
threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer))
{
memset (tp, 0, sizeof (ThreadPool));
tp->min_threads = min_threads;
tp->max_threads = max_threads;
tp->async_invoke = async_invoke;
tp->queue = mono_cq_create ();
MONO_SEM_INIT (&tp->new_job, 0);
}
#ifndef DISABLE_PERFCOUNTERS
static void *
init_perf_counter (const char *category, const char *counter)
{
MonoString *category_str;
MonoString *counter_str;
MonoString *machine;
MonoDomain *root;
MonoBoolean custom;
int type;
if (category == NULL || counter == NULL)
return NULL;
root = mono_get_root_domain ();
category_str = mono_string_new (root, category);
counter_str = mono_string_new (root, counter);
machine = mono_string_new (root, ".");
return mono_perfcounter_get_impl (category_str, counter_str, NULL, machine, &type, &custom);
}
#endif
#ifdef DEBUG
static void
print_pool_info (ThreadPool *tp)
{
// if (tp->tail - tp->head == 0)
// return;
g_print ("Pool status? %d\n", InterlockedCompareExchange (&tp->pool_status, 0, 0));
g_print ("Min. threads: %d\n", InterlockedCompareExchange (&tp->min_threads, 0, 0));
g_print ("Max. threads: %d\n", InterlockedCompareExchange (&tp->max_threads, 0, 0));
g_print ("nthreads: %d\n", InterlockedCompareExchange (&tp->nthreads, 0, 0));
g_print ("busy threads: %d\n", InterlockedCompareExchange (&tp->busy_threads, 0, 0));
g_print ("Waiting: %d\n", InterlockedCompareExchange (&tp->waiting, 0, 0));
g_print ("Queued: %d\n", (tp->tail - tp->head));
if (tp == &async_tp) {
int i;
EnterCriticalSection (&wsqs_lock);
for (i = 0; i < wsqs->len; i++) {
g_print ("\tWSQ %d: %d\n", i, mono_wsq_count (g_ptr_array_index (wsqs, i)));
}
LeaveCriticalSection (&wsqs_lock);
} else {
g_print ("\tSockets: %d\n", mono_g_hash_table_size (socket_io_data.sock_to_state));
}
g_print ("-------------\n");
}
static void
signal_handler (int signo)
{
ThreadPool *tp;
tp = &async_tp;
g_print ("\n-----Non-IO-----\n");
print_pool_info (tp);
tp = &async_io_tp;
g_print ("\n-----IO-----\n");
print_pool_info (tp);
alarm (2);
}
#endif
static void
monitor_thread (gpointer unused)
{
ThreadPool *pools [2];
MonoInternalThread *thread;
guint32 ms;
gboolean need_one;
int i;
pools [0] = &async_tp;
pools [1] = &async_io_tp;
thread = mono_thread_internal_current ();
ves_icall_System_Threading_Thread_SetName_internal (thread, mono_string_new (mono_domain_get (), "Threadpool monitor"));
while (1) {
ms = 500;
i = 10; //number of spurious awakes we tolerate before doing a round of rebalancing.
do {
guint32 ts;
ts = mono_msec_ticks ();
if (SleepEx (ms, TRUE) == 0)
break;
ms -= (mono_msec_ticks () - ts);
if (mono_runtime_is_shutting_down ())
break;
if (THREAD_WANTS_A_BREAK (thread))
mono_thread_interruption_checkpoint ();
} while (ms > 0 && i--);
if (mono_runtime_is_shutting_down ())
break;
if (suspended)
continue;
for (i = 0; i < 2; i++) {
ThreadPool *tp;
tp = pools [i];
if (tp->waiting > 0)
continue;
need_one = (mono_cq_count (tp->queue) > 0);
if (!need_one && !tp->is_io) {
EnterCriticalSection (&wsqs_lock);
for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
MonoWSQ *wsq;
wsq = g_ptr_array_index (wsqs, i);
if (mono_wsq_count (wsq) != 0) {
need_one = TRUE;
break;
}
}
LeaveCriticalSection (&wsqs_lock);
}
if (need_one)
threadpool_start_thread (tp);
}
}
}
void
mono_thread_pool_init_tls (void)
{
mono_wsq_init ();
}
void
mono_thread_pool_init (void)
{
gint threads_per_cpu = 1;
gint thread_count;
gint cpu_count = mono_cpu_count ();
int result;
if (tp_inited == 2)
return;
result = InterlockedCompareExchange (&tp_inited, 1, 0);
if (result == 1) {
while (1) {
SleepEx (1, FALSE);
if (tp_inited == 2)
return;
}
}
MONO_GC_REGISTER_ROOT_FIXED (socket_io_data.sock_to_state);
InitializeCriticalSection (&socket_io_data.io_lock);
if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
if (threads_per_cpu < 1)
threads_per_cpu = 1;
}
thread_count = MIN (cpu_count * threads_per_cpu, 100 * cpu_count);
threadpool_init (&async_tp, thread_count, MAX (100 * cpu_count, thread_count), async_invoke_thread);
threadpool_init (&async_io_tp, cpu_count * 2, cpu_count * 4, async_invoke_thread);
async_io_tp.is_io = TRUE;
async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
g_assert (async_call_klass);
InitializeCriticalSection (&wsqs_lock);
wsqs = g_ptr_array_sized_new (MAX (100 * cpu_count, thread_count));
#ifndef DISABLE_PERFCOUNTERS
async_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "Work Items Added");
g_assert (async_tp.pc_nitems);
async_io_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "IO Work Items Added");
g_assert (async_io_tp.pc_nitems);
async_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of Threads");
g_assert (async_tp.pc_nthreads);
async_io_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of IO Threads");
g_assert (async_io_tp.pc_nthreads);
#endif
tp_inited = 2;
#ifdef DEBUG
signal (SIGALRM, signal_handler);
alarm (2);
#endif
}
static MonoAsyncResult *
create_simple_asyncresult (MonoObject *target, MonoObject *state)
{
MonoDomain *domain = mono_domain_get ();
MonoAsyncResult *ares;
/* Don't call mono_async_result_new() to avoid capturing the context */
ares = (MonoAsyncResult *) mono_object_new (domain, mono_defaults.asyncresult_class);
MONO_OBJECT_SETREF (ares, async_delegate, target);
MONO_OBJECT_SETREF (ares, async_state, state);
return ares;
}
void
icall_append_io_job (MonoObject *target, MonoSocketAsyncResult *state)
{
MonoAsyncResult *ares;
ares = create_simple_asyncresult (target, (MonoObject *) state);
socket_io_add (ares, state);
}
MonoAsyncResult *
mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
MonoObject *state)
{
MonoDomain *domain = mono_domain_get ();
MonoAsyncResult *ares;
ASyncCall *ac;
ac = (ASyncCall*)mono_object_new (domain, async_call_klass);
MONO_OBJECT_SETREF (ac, msg, msg);
MONO_OBJECT_SETREF (ac, state, state);
if (async_callback) {
ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
MONO_OBJECT_SETREF (ac, cb_target, async_callback);
}
ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
MONO_OBJECT_SETREF (ares, async_delegate, target);
#ifndef DISABLE_SOCKETS
if (socket_io_filter (target, state)) {
socket_io_add (ares, (MonoSocketAsyncResult *) state);
return ares;
}
#endif
threadpool_append_job (&async_tp, (MonoObject *) ares);
return ares;
}
MonoObject *
mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
{
ASyncCall *ac;
HANDLE wait_event;
*exc = NULL;
*out_args = NULL;
/* check if already finished */
mono_monitor_enter ((MonoObject *) ares);
if (ares->endinvoke_called) {
*exc = (MonoObject *) mono_get_exception_invalid_operation (NULL);
mono_monitor_exit ((MonoObject *) ares);
return NULL;
}
ares->endinvoke_called = 1;
/* wait until we are really finished */
if (!ares->completed) {
if (ares->handle == NULL) {
wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
g_assert(wait_event != 0);
MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), wait_event));
} else {
wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
}
mono_monitor_exit ((MonoObject *) ares);
WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
} else {
mono_monitor_exit ((MonoObject *) ares);
}
ac = (ASyncCall *) ares->object_data;
g_assert (ac != NULL);
*exc = ac->msg->exc; /* FIXME: GC add write barrier */
*out_args = ac->out_args;
return ac->res;
}
static void
threadpool_kill_idle_threads (ThreadPool *tp)
{
gint n;
n = (gint) InterlockedCompareExchange (&tp->max_threads, 0, -1);
while (n) {
n--;
MONO_SEM_POST (&tp->new_job);
}
}
void
mono_thread_pool_cleanup (void)
{
if (InterlockedExchange (&async_io_tp.pool_status, 2) == 1) {
socket_io_cleanup (&socket_io_data); /* Empty when DISABLE_SOCKETS is defined */
threadpool_kill_idle_threads (&async_io_tp);
}
if (async_io_tp.queue != NULL) {
MONO_SEM_DESTROY (&async_io_tp.new_job);
threadpool_free_queue (&async_io_tp);
}