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/appdomain.h>
21 #include <mono/metadata/tabledefs.h>
22 #include <mono/metadata/threads.h>
23 #include <mono/metadata/exception.h>
24 #include <mono/metadata/file-io.h>
25 #include <mono/metadata/monitor.h>
26 #include <mono/metadata/marshal.h>
27 #include <mono/io-layer/io-layer.h>
28 #include <mono/os/gc_wrapper.h>
30 #include "threadpool.h"
32 /* maximum number of worker threads */
33 int mono_max_worker_threads = 25; /* fixme: should be 25 per available CPU */
34 int mono_min_worker_threads = 0;
36 /* current number of worker threads */
37 static int mono_worker_threads = 0;
39 /* current number of busy threads */
40 int busy_worker_threads = 0;
42 /* we use this to store a reference to the AsyncResult to avoid GC */
43 static MonoGHashTable *ares_htable = NULL;
46 static HANDLE job_added;
49 MonoMethodMessage *msg;
51 MonoMethod *cb_method;
52 MonoDelegate *cb_target;
58 static void async_invoke_thread (gpointer data);
59 static void append_job (MonoAsyncResult *ar);
61 static GList *async_call_queue = NULL;
64 mono_async_invoke (MonoAsyncResult *ares)
66 ASyncCall *ac = (ASyncCall *)ares->data;
69 ac->res = mono_message_invoke (ares->async_delegate, ac->msg,
70 &ac->msg->exc, &ac->out_args);
74 /* call async callback if cb_method != null*/
76 MonoObject *exc = NULL;
78 mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &exc);
83 /* notify listeners */
84 if(!mono_monitor_try_enter ((MonoObject *) ares, INFINITE))
87 if (ares->handle != NULL) {
88 ac->wait_event = ((MonoWaitHandle *) ares->handle)->handle;
89 SetEvent (ac->wait_event);
91 mono_monitor_exit ((MonoObject *) ares);
93 mono_g_hash_table_remove (ares_htable, ares);
97 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
100 MonoDomain *domain = mono_domain_get ();
101 MonoAsyncResult *ares;
106 ac = GC_MALLOC (sizeof (ASyncCall));
108 /* We'll leak the event if creaated... */
109 ac = g_new0 (ASyncCall, 1);
111 ac->wait_event = NULL;
115 if (async_callback) {
116 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
117 ac->cb_target = async_callback;
120 ares = mono_async_result_new (domain, NULL, ac->state, ac);
121 ares->async_delegate = target;
124 ares_htable = mono_g_hash_table_new (NULL, NULL);
125 job_added = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
128 mono_g_hash_table_insert (ares_htable, ares, ares);
130 busy = (int) InterlockedCompareExchange (&busy_worker_threads, 0, -1);
131 worker = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
132 if (worker <= ++busy &&
133 worker < mono_max_worker_threads) {
134 InterlockedIncrement (&mono_worker_threads);
135 InterlockedIncrement (&busy_worker_threads);
136 mono_thread_create (domain, async_invoke_thread, ares);
139 ReleaseSemaphore (job_added, 1, NULL);
146 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
153 /* check if already finished */
154 if (!mono_monitor_try_enter ((MonoObject *) ares, INFINITE)) {
158 if (ares->endinvoke_called) {
159 *exc = (MonoObject *)mono_exception_from_name (mono_defaults.corlib, "System",
160 "InvalidOperationException");
161 mono_monitor_exit ((MonoObject *) ares);
165 ares->endinvoke_called = 1;
166 ac = (ASyncCall *)ares->data;
168 g_assert (ac != NULL);
170 /* wait until we are really finished */
171 if (!ares->completed) {
172 if (ares->handle == NULL) {
173 ac->wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
174 ares->handle = (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), ac->wait_event);
176 mono_monitor_exit ((MonoObject *) ares);
177 WaitForSingleObjectEx (ac->wait_event, INFINITE, TRUE);
179 mono_monitor_exit ((MonoObject *) ares);
183 *out_args = ac->out_args;
189 mono_thread_pool_cleanup (void)
193 EnterCriticalSection (&mono_delegate_section);
194 g_list_free (async_call_queue);
195 async_call_queue = NULL;
196 release = (gint) InterlockedCompareExchange (&busy_worker_threads, 0, -1);
197 LeaveCriticalSection (&mono_delegate_section);
199 ReleaseSemaphore (job_added, release, NULL);
203 append_job (MonoAsyncResult *ar)
205 EnterCriticalSection (&mono_delegate_section);
206 async_call_queue = g_list_append (async_call_queue, ar);
207 LeaveCriticalSection (&mono_delegate_section);
210 static MonoAsyncResult *
213 MonoAsyncResult *ar = NULL;
216 EnterCriticalSection (&mono_delegate_section);
217 if (async_call_queue) {
218 ar = (MonoAsyncResult *)async_call_queue->data;
219 tmp = async_call_queue;
220 async_call_queue = g_list_remove_link (tmp, tmp);
222 LeaveCriticalSection (&mono_delegate_section);
230 async_invoke_thread (gpointer data)
236 thread = mono_thread_current ();
237 thread->threadpool_thread = TRUE;
238 thread->state |= ThreadState_Background;
242 ar = (MonoAsyncResult *) data;
244 /* worker threads invokes methods in different domains,
245 * so we need to set the right domain here */
246 domain = ((MonoObject *)ar)->vtable->domain;
247 if (mono_domain_set (domain, FALSE))
248 mono_async_invoke (ar);
249 InterlockedDecrement (&busy_worker_threads);
252 data = dequeue_job ();
257 guint32 start_time = GetTickCount ();
260 wr = WaitForSingleObjectEx (job_added, (guint32)timeout, TRUE);
261 mono_thread_interruption_checkpoint ();
263 timeout -= GetTickCount () - start_time;
265 if (wr != WAIT_TIMEOUT)
266 data = dequeue_job ();
268 while (!data && timeout > 0);
272 workers = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
273 min = (int) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
275 while (!data && workers <= min) {
276 WaitForSingleObjectEx (job_added, INFINITE, TRUE);
277 mono_thread_interruption_checkpoint ();
279 data = dequeue_job ();
280 workers = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
281 min = (int) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
286 InterlockedDecrement (&mono_worker_threads);
290 InterlockedIncrement (&busy_worker_threads);
293 g_assert_not_reached ();
297 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
303 busy = (gint) InterlockedCompareExchange (&busy_worker_threads, 0, -1);
304 *workerThreads = mono_max_worker_threads - busy;
305 *completionPortThreads = 0;
309 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
313 *workerThreads = mono_max_worker_threads;
314 *completionPortThreads = 0;
318 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
324 workers = (gint) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
325 *workerThreads = workers;
326 *completionPortThreads = 0;
330 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
334 InterlockedExchange (&mono_min_worker_threads, workerThreads);
338 overlapped_callback (guint32 error, guint32 numbytes, WapiOverlapped *overlapped)
340 MonoFSAsyncResult *ares;
345 ares = (MonoFSAsyncResult *) overlapped->handle1;
346 ares->completed = TRUE;
347 if (ares->bytes_read != -1)
348 ares->bytes_read = numbytes;
350 ares->count = numbytes;
352 thread = mono_thread_attach (mono_object_domain (ares));
353 if (ares->async_callback != NULL) {
357 mono_runtime_invoke (ares->async_callback->method_info->method, NULL, p, NULL);
360 SetEvent (ares->wait_handle->handle);
361 mono_thread_detach (thread);
366 ves_icall_System_Threading_ThreadPool_BindHandle (gpointer handle)
370 #ifdef PLATFORM_WIN32
373 if (!BindIoCompletionCallback (handle, overlapped_callback, 0)) {
374 gint error = GetLastError ();
378 if (error == ERROR_INVALID_PARAMETER) {
379 exc = mono_get_exception_argument (NULL, "Invalid parameter.");
381 msg = g_strdup_printf ("Win32 error %d.", error);
382 exc = mono_exception_from_name_msg (mono_defaults.corlib,
384 "ApplicationException", msg);
388 mono_raise_exception (exc);