2 * threadpool.c: global thread pool
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Gonzalo Paniagua Javier (gonzalo@ximian.com)
8 * (C) 2001-2003 Ximian, Inc.
9 * (c) 2004 Novell, Inc. (http://www.novell.com)
17 #define _WIN32_WINNT 0x0500
20 #include <mono/metadata/domain-internals.h>
21 #include <mono/metadata/tabledefs.h>
22 #include <mono/metadata/threads.h>
23 #include <mono/metadata/threads-types.h>
24 #include <mono/metadata/exception.h>
25 #include <mono/metadata/file-io.h>
26 #include <mono/metadata/monitor.h>
27 #include <mono/metadata/marshal.h>
28 #include <mono/io-layer/io-layer.h>
29 #include <mono/os/gc_wrapper.h>
31 #include "threadpool.h"
33 /* maximum number of worker threads */
34 int mono_max_worker_threads = 25; /* fixme: should be 25 per available CPU */
35 static int mono_min_worker_threads = 0;
37 /* current number of worker threads */
38 static int mono_worker_threads = 0;
40 /* current number of busy threads */
41 static int busy_worker_threads = 0;
43 /* we use this to store a reference to the AsyncResult to avoid GC */
44 static MonoGHashTable *ares_htable = NULL;
47 static HANDLE job_added;
50 MonoMethodMessage *msg;
52 MonoMethod *cb_method;
53 MonoDelegate *cb_target;
59 static void async_invoke_thread (gpointer data);
60 static void append_job (MonoAsyncResult *ar);
62 static GList *async_call_queue = NULL;
65 mono_async_invoke (MonoAsyncResult *ares)
67 ASyncCall *ac = (ASyncCall *)ares->data;
70 ac->res = mono_message_invoke (ares->async_delegate, ac->msg,
71 &ac->msg->exc, &ac->out_args);
75 /* call async callback if cb_method != null*/
77 MonoObject *exc = NULL;
79 mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &exc);
84 /* notify listeners */
85 if(!mono_monitor_enter ((MonoObject *) ares))
88 if (ares->handle != NULL) {
89 ac->wait_event = ((MonoWaitHandle *) ares->handle)->handle;
90 SetEvent (ac->wait_event);
92 mono_monitor_exit ((MonoObject *) ares);
94 mono_g_hash_table_remove (ares_htable, ares);
98 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
101 MonoDomain *domain = mono_domain_get ();
102 MonoAsyncResult *ares;
107 ac = GC_MALLOC (sizeof (ASyncCall));
109 /* We'll leak the event if creaated... */
110 ac = g_new0 (ASyncCall, 1);
112 ac->wait_event = NULL;
116 if (async_callback) {
117 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
118 ac->cb_target = async_callback;
121 ares = mono_async_result_new (domain, NULL, ac->state, ac);
122 ares->async_delegate = target;
125 MONO_GC_REGISTER_ROOT (ares_htable);
126 ares_htable = mono_g_hash_table_new (NULL, NULL);
127 job_added = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
130 mono_g_hash_table_insert (ares_htable, ares, ares);
132 busy = (int) InterlockedCompareExchange (&busy_worker_threads, 0, -1);
133 worker = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
134 if (worker <= ++busy &&
135 worker < mono_max_worker_threads) {
136 InterlockedIncrement (&mono_worker_threads);
137 InterlockedIncrement (&busy_worker_threads);
138 mono_thread_create (domain, async_invoke_thread, ares);
141 ReleaseSemaphore (job_added, 1, NULL);
148 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
155 /* check if already finished */
156 if (!mono_monitor_enter ((MonoObject *) ares)) {
160 if (ares->endinvoke_called) {
161 *exc = (MonoObject *)mono_exception_from_name (mono_defaults.corlib, "System",
162 "InvalidOperationException");
163 mono_monitor_exit ((MonoObject *) ares);
167 ares->endinvoke_called = 1;
168 ac = (ASyncCall *)ares->data;
170 g_assert (ac != NULL);
172 /* wait until we are really finished */
173 if (!ares->completed) {
174 if (ares->handle == NULL) {
175 ac->wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
176 ares->handle = (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), ac->wait_event);
178 mono_monitor_exit ((MonoObject *) ares);
179 WaitForSingleObjectEx (ac->wait_event, INFINITE, TRUE);
181 mono_monitor_exit ((MonoObject *) ares);
185 *out_args = ac->out_args;
191 mono_thread_pool_cleanup (void)
195 EnterCriticalSection (&mono_delegate_section);
196 g_list_free (async_call_queue);
197 async_call_queue = NULL;
198 release = (gint) InterlockedCompareExchange (&busy_worker_threads, 0, -1);
199 LeaveCriticalSection (&mono_delegate_section);
201 ReleaseSemaphore (job_added, release, NULL);
205 append_job (MonoAsyncResult *ar)
207 EnterCriticalSection (&mono_delegate_section);
208 async_call_queue = g_list_append (async_call_queue, ar);
209 LeaveCriticalSection (&mono_delegate_section);
212 static MonoAsyncResult *
215 MonoAsyncResult *ar = NULL;
218 EnterCriticalSection (&mono_delegate_section);
219 if (async_call_queue) {
220 ar = (MonoAsyncResult *)async_call_queue->data;
221 tmp = async_call_queue;
222 async_call_queue = g_list_remove_link (tmp, tmp);
224 LeaveCriticalSection (&mono_delegate_section);
232 async_invoke_thread (gpointer data)
238 thread = mono_thread_current ();
239 thread->threadpool_thread = TRUE;
240 thread->state |= ThreadState_Background;
244 ar = (MonoAsyncResult *) data;
246 /* worker threads invokes methods in different domains,
247 * so we need to set the right domain here */
248 domain = ((MonoObject *)ar)->vtable->domain;
249 if (mono_domain_set (domain, FALSE))
250 mono_async_invoke (ar);
251 InterlockedDecrement (&busy_worker_threads);
254 data = dequeue_job ();
259 guint32 start_time = GetTickCount ();
262 wr = WaitForSingleObjectEx (job_added, (guint32)timeout, TRUE);
263 mono_thread_interruption_checkpoint ();
265 timeout -= GetTickCount () - start_time;
267 if (wr != WAIT_TIMEOUT)
268 data = dequeue_job ();
270 while (!data && timeout > 0);
274 workers = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
275 min = (int) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
277 while (!data && workers <= min) {
278 WaitForSingleObjectEx (job_added, INFINITE, TRUE);
279 mono_thread_interruption_checkpoint ();
281 data = dequeue_job ();
282 workers = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
283 min = (int) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
288 InterlockedDecrement (&mono_worker_threads);
292 InterlockedIncrement (&busy_worker_threads);
295 g_assert_not_reached ();
299 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
305 busy = (gint) InterlockedCompareExchange (&busy_worker_threads, 0, -1);
306 *workerThreads = mono_max_worker_threads - busy;
307 *completionPortThreads = 0;
311 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
315 *workerThreads = mono_max_worker_threads;
316 *completionPortThreads = 0;
320 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
326 workers = (gint) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
327 *workerThreads = workers;
328 *completionPortThreads = 0;
332 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
336 if (workerThreads < 0 || workerThreads > mono_max_worker_threads)
338 InterlockedExchange (&mono_min_worker_threads, workerThreads);
339 /* FIXME: should actually start the idle threads if needed */
344 overlapped_callback (guint32 error, guint32 numbytes, WapiOverlapped *overlapped)
346 MonoFSAsyncResult *ares;
351 ares = (MonoFSAsyncResult *) overlapped->handle1;
352 ares->completed = TRUE;
353 if (ares->bytes_read != -1)
354 ares->bytes_read = numbytes;
356 ares->count = numbytes;
358 thread = mono_thread_attach (mono_object_domain (ares));
359 if (ares->async_callback != NULL) {
363 mono_runtime_invoke (ares->async_callback->method_info->method, NULL, p, NULL);
366 SetEvent (ares->wait_handle->handle);
367 mono_thread_detach (thread);
372 ves_icall_System_Threading_ThreadPool_BindHandle (gpointer handle)
376 #ifdef PLATFORM_WIN32
379 if (!BindIoCompletionCallback (handle, overlapped_callback, 0)) {
380 gint error = GetLastError ();
384 if (error == ERROR_INVALID_PARAMETER) {
385 exc = mono_get_exception_argument (NULL, "Invalid parameter.");
387 msg = g_strdup_printf ("Win32 error %d.", error);
388 exc = mono_exception_from_name_msg (mono_defaults.corlib,
390 "ApplicationException", msg);
394 mono_raise_exception (exc);