1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * GAsyncQueue: thread pool implementation.
5 * Copyright (C) 2000 Sebastian Wilhelmi; University of Karlsruhe
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
33 typedef struct _GRealThreadPool GRealThreadPool;
35 struct _GRealThreadPool
46 /* The following is just an address to mark the stop order for a
47 * thread, it could be any address (as long, as it isn't a valid
48 * GThreadPool address) */
49 static const gpointer stop_this_thread_marker = (gpointer) &g_thread_pool_new;
51 /* Here all unused threads are waiting */
52 static GAsyncQueue *unused_thread_queue;
53 static gint unused_threads = 0;
54 static gint max_unused_threads = 0;
55 G_LOCK_DEFINE_STATIC (unused_threads);
57 static GMutex *inform_mutex = NULL;
58 static GCond *inform_cond = NULL;
60 static void g_thread_pool_free_internal (GRealThreadPool* pool);
61 static gpointer g_thread_pool_thread_proxy (gpointer data);
62 static void g_thread_pool_start_thread (GRealThreadPool* pool,
64 static void g_thread_pool_wakeup_and_stop_all (GRealThreadPool* pool);
66 #define g_thread_should_run(pool, len) \
67 ((pool)->running || (!(pool)->immediate && (len) > 0))
70 g_thread_pool_thread_proxy (gpointer data)
72 GRealThreadPool *pool = data;
73 gboolean watcher = FALSE;
75 g_async_queue_lock (pool->queue);
79 gboolean goto_global_pool = !pool->pool.exclusive;
80 gint len = g_async_queue_length_unlocked (pool->queue);
82 if (g_thread_should_run (pool, len))
86 /* This thread is actually not needed here, but it waits
87 * for some time anyway. If during that time a new
88 * request arrives, this saves process
89 * swicthes. Otherwise the thread will go to the global
92 g_get_current_time (&end_time);
93 g_time_val_add (&end_time, G_USEC_PER_SEC / 2); /* 1/2 second */
94 task = g_async_queue_timed_pop_unlocked (pool->queue, &end_time);
97 task = g_async_queue_pop_unlocked (pool->queue);
102 if (pool->num_threads > pool->max_threads &&
103 pool->max_threads != -1)
104 /* We are in fact a superfluous threads, so we go to
105 * the global pool and just hand the data further to
106 * the next one waiting in the queue */
108 g_async_queue_push_unlocked (pool->queue, task);
109 goto_global_pool = TRUE;
111 else if (pool->running || !pool->immediate)
113 g_async_queue_unlock (pool->queue);
114 pool->pool.func (task, pool->pool.user_data);
115 g_async_queue_lock (pool->queue);
118 len = g_async_queue_length_unlocked (pool->queue);
121 if (!g_thread_should_run (pool, len))
123 g_cond_broadcast (inform_cond);
124 goto_global_pool = TRUE;
128 /* At this pool there are no threads waiting, but tasks are. */
129 goto_global_pool = FALSE;
131 else if (len == 0 && !watcher && !pool->pool.exclusive)
133 /* Here neither threads nor tasks are queued and we didn't
134 * just return from a timed wait. We now wait for a limited
135 * time at this pool for new tasks to avoid costly context
137 goto_global_pool = FALSE;
141 if (goto_global_pool)
145 if (!pool->running && !pool->waiting)
147 if (pool->num_threads == 0)
149 g_async_queue_unlock (pool->queue);
150 g_thread_pool_free_internal (pool);
154 if (len == - pool->num_threads)
155 g_thread_pool_wakeup_and_stop_all (pool);
157 g_async_queue_unlock (pool->queue);
161 g_async_queue_unlock (pool->queue);
163 g_async_queue_lock (unused_thread_queue);
165 G_LOCK (unused_threads);
166 if ((unused_threads >= max_unused_threads &&
167 max_unused_threads != -1))
169 G_UNLOCK (unused_threads);
170 g_async_queue_unlock (unused_thread_queue);
171 /* Stop this thread */
175 G_UNLOCK (unused_threads);
177 pool = g_async_queue_pop_unlocked (unused_thread_queue);
179 G_LOCK (unused_threads);
181 G_UNLOCK (unused_threads);
183 g_async_queue_unlock (unused_thread_queue);
185 if (pool == stop_this_thread_marker)
186 /* Stop this thread */
189 g_async_queue_lock (pool->queue);
191 /* pool->num_threads++ is not done here, but in
192 * g_thread_pool_start_thread to make the new started thread
193 * known to the pool, before itself can do it. */
200 g_thread_pool_start_thread (GRealThreadPool *pool,
203 gboolean success = FALSE;
205 if (pool->num_threads >= pool->max_threads && pool->max_threads != -1)
206 /* Enough threads are already running */
209 g_async_queue_lock (unused_thread_queue);
211 if (g_async_queue_length_unlocked (unused_thread_queue) < 0)
213 g_async_queue_push_unlocked (unused_thread_queue, pool);
217 g_async_queue_unlock (unused_thread_queue);
221 GError *local_error = NULL;
222 /* No thread was found, we have to start a new one */
223 g_thread_create (g_thread_pool_thread_proxy, pool, FALSE, &local_error);
227 g_propagate_error (error, local_error);
232 /* See comment in g_thread_pool_thread_proxy as to why this is done
233 * here and not there */
239 * @func: a function to execute in the threads of the new thread pool
240 * @user_data: user data that is handed over to @func every time it
242 * @max_threads: the maximal number of threads to execute concurrently in
243 * the new thread pool, -1 means no limit
244 * @exclusive: should this thread pool be exclusive?
245 * @error: return location for error
247 * This function creates a new thread pool.
249 * Whenever you call g_thread_pool_push(), either a new thread is
250 * created or an unused one is reused. At most @max_threads threads
251 * are running concurrently for this thread pool. @max_threads = -1
252 * allows unlimited threads to be created for this thread pool. The
253 * newly created or reused thread now executes the function @func with
254 * the two arguments. The first one is the parameter to
255 * g_thread_pool_push() and the second one is @user_data.
257 * The parameter @exclusive determines, whether the thread pool owns
258 * all threads exclusive or whether the threads are shared
259 * globally. If @exclusive is %TRUE, @max_threads threads are started
260 * immediately and they will run exclusively for this thread pool until
261 * it is destroyed by g_thread_pool_free(). If @exclusive is %FALSE,
262 * threads are created, when needed and shared between all
263 * non-exclusive thread pools. This implies that @max_threads may not
264 * be -1 for exclusive thread pools.
266 * @error can be %NULL to ignore errors, or non-%NULL to report
267 * errors. An error can only occur when @exclusive is set to %TRUE and
268 * not all @max_threads threads could be created.
270 * Return value: the new #GThreadPool
273 g_thread_pool_new (GFunc func,
279 GRealThreadPool *retval;
280 G_LOCK_DEFINE_STATIC (init);
282 g_return_val_if_fail (func, NULL);
283 g_return_val_if_fail (!exclusive || max_threads != -1, NULL);
284 g_return_val_if_fail (max_threads >= -1, NULL);
285 g_return_val_if_fail (g_thread_supported (), NULL);
287 retval = g_new (GRealThreadPool, 1);
289 retval->pool.func = func;
290 retval->pool.user_data = user_data;
291 retval->pool.exclusive = exclusive;
292 retval->queue = g_async_queue_new ();
293 retval->max_threads = max_threads;
294 retval->num_threads = 0;
295 retval->running = TRUE;
301 inform_mutex = g_mutex_new ();
302 inform_cond = g_cond_new ();
303 unused_thread_queue = g_async_queue_new ();
308 if (retval->pool.exclusive)
310 g_async_queue_lock (retval->queue);
312 while (retval->num_threads < retval->max_threads)
314 GError *local_error = NULL;
315 g_thread_pool_start_thread (retval, &local_error);
318 g_propagate_error (error, local_error);
323 g_async_queue_unlock (retval->queue);
326 return (GThreadPool*) retval;
330 * g_thread_pool_push:
331 * @pool: a #GThreadPool
332 * @data: a new task for @pool
333 * @error: return location for error
335 * Inserts @data into the list of tasks to be executed by @pool. When
336 * the number of currently running threads is lower than the maximal
337 * allowed number of threads, a new thread is started (or reused) with
338 * the properties given to g_thread_pool_new (). Otherwise @data stays
339 * in the queue until a thread in this pool finishes its previous task
340 * and processes @data.
342 * @error can be %NULL to ignore errors, or non-%NULL to report
343 * errors. An error can only occur when a new thread couldn't be
344 * created. In that case @data is simply appended to the queue of work
348 g_thread_pool_push (GThreadPool *pool,
352 GRealThreadPool *real = (GRealThreadPool*) pool;
354 g_return_if_fail (real);
356 g_async_queue_lock (real->queue);
360 g_async_queue_unlock (real->queue);
361 g_return_if_fail (real->running);
364 if (g_async_queue_length_unlocked (real->queue) >= 0)
365 /* No thread is waiting in the queue */
366 g_thread_pool_start_thread (real, error);
368 g_async_queue_push_unlocked (real->queue, data);
369 g_async_queue_unlock (real->queue);
373 * g_thread_pool_set_max_threads:
374 * @pool: a #GThreadPool
375 * @max_threads: a new maximal number of threads for @pool
376 * @error: return location for error
378 * Sets the maximal allowed number of threads for @pool. A value of -1
379 * means, that the maximal number of threads is unlimited.
381 * Setting @max_threads to 0 means stopping all work for @pool. It is
382 * effectively frozen until @max_threads is set to a non-zero value
385 * A thread is never terminated while calling @func, as supplied by
386 * g_thread_pool_new (). Instead the maximal number of threads only
387 * has effect for the allocation of new threads in g_thread_pool_push().
388 * A new thread is allocated, whenever the number of currently
389 * running threads in @pool is smaller than the maximal number.
391 * @error can be %NULL to ignore errors, or non-%NULL to report
392 * errors. An error can only occur when a new thread couldn't be
396 g_thread_pool_set_max_threads (GThreadPool *pool,
400 GRealThreadPool *real = (GRealThreadPool*) pool;
403 g_return_if_fail (real);
404 g_return_if_fail (real->running);
405 g_return_if_fail (!real->pool.exclusive || max_threads != -1);
406 g_return_if_fail (max_threads >= -1);
408 g_async_queue_lock (real->queue);
410 real->max_threads = max_threads;
413 to_start = real->max_threads - real->num_threads;
415 to_start = g_async_queue_length_unlocked (real->queue);
417 for ( ; to_start > 0; to_start--)
419 GError *local_error = NULL;
420 g_thread_pool_start_thread (real, &local_error);
423 g_propagate_error (error, local_error);
428 g_async_queue_unlock (real->queue);
432 * g_thread_pool_get_max_threads:
433 * @pool: a #GThreadPool
435 * Returns the maximal number of threads for @pool.
437 * Return value: the maximal number of threads
440 g_thread_pool_get_max_threads (GThreadPool *pool)
442 GRealThreadPool *real = (GRealThreadPool*) pool;
445 g_return_val_if_fail (real, 0);
446 g_return_val_if_fail (real->running, 0);
448 g_async_queue_lock (real->queue);
450 retval = real->max_threads;
452 g_async_queue_unlock (real->queue);
458 * g_thread_pool_get_num_threads:
459 * @pool: a #GThreadPool
461 * Returns the number of threads currently running in @pool.
463 * Return value: the number of threads currently running
466 g_thread_pool_get_num_threads (GThreadPool *pool)
468 GRealThreadPool *real = (GRealThreadPool*) pool;
471 g_return_val_if_fail (real, 0);
472 g_return_val_if_fail (real->running, 0);
474 g_async_queue_lock (real->queue);
476 retval = real->num_threads;
478 g_async_queue_unlock (real->queue);
484 * g_thread_pool_unprocessed:
485 * @pool: a #GThreadPool
487 * Returns the number of tasks still unprocessed in @pool.
489 * Return value: the number of unprocessed tasks
492 g_thread_pool_unprocessed (GThreadPool *pool)
494 GRealThreadPool *real = (GRealThreadPool*) pool;
497 g_return_val_if_fail (real, 0);
498 g_return_val_if_fail (real->running, 0);
500 unprocessed = g_async_queue_length (real->queue);
502 return MAX (unprocessed, 0);
506 * g_thread_pool_free:
507 * @pool: a #GThreadPool
508 * @immediate: should @pool shut down immediately?
509 * @wait: should the function wait for all tasks to be finished?
511 * Frees all resources allocated for @pool.
513 * If @immediate is %TRUE, no new task is processed for
514 * @pool. Otherwise @pool is not freed before the last task is
515 * processed. Note however, that no thread of this pool is
516 * interrupted, while processing a task. Instead at least all still
517 * running threads can finish their tasks before the @pool is freed.
519 * If @wait is %TRUE, the functions does not return before all tasks
520 * to be processed (dependent on @immediate, whether all or only the
521 * currently running) are ready. Otherwise the function returns immediately.
523 * After calling this function @pool must not be used anymore.
526 g_thread_pool_free (GThreadPool *pool,
530 GRealThreadPool *real = (GRealThreadPool*) pool;
532 g_return_if_fail (real);
533 g_return_if_fail (real->running);
534 /* It there's no thread allowed here, there is not much sense in
535 * not stopping this pool immediately, when it's not empty */
536 g_return_if_fail (immediate || real->max_threads != 0 ||
537 g_async_queue_length (real->queue) == 0);
539 g_async_queue_lock (real->queue);
541 real->running = FALSE;
542 real->immediate = immediate;
543 real->waiting = wait;
547 g_mutex_lock (inform_mutex);
548 while (g_async_queue_length_unlocked (real->queue) != -real->num_threads)
550 g_async_queue_unlock (real->queue);
551 g_cond_wait (inform_cond, inform_mutex);
552 g_async_queue_lock (real->queue);
554 g_mutex_unlock (inform_mutex);
557 if (g_async_queue_length_unlocked (real->queue) == -real->num_threads)
559 /* No thread is currently doing something (and nothing is left
560 * to process in the queue) */
561 if (real->num_threads == 0) /* No threads left, we clean up */
563 g_async_queue_unlock (real->queue);
564 g_thread_pool_free_internal (real);
568 g_thread_pool_wakeup_and_stop_all (real);
571 real->waiting = FALSE; /* The last thread should cleanup the pool */
572 g_async_queue_unlock (real->queue);
576 g_thread_pool_free_internal (GRealThreadPool* pool)
578 g_return_if_fail (pool);
579 g_return_if_fail (!pool->running);
580 g_return_if_fail (pool->num_threads == 0);
582 g_async_queue_unref (pool->queue);
588 g_thread_pool_wakeup_and_stop_all (GRealThreadPool* pool)
592 g_return_if_fail (pool);
593 g_return_if_fail (!pool->running);
594 g_return_if_fail (pool->num_threads != 0);
595 g_return_if_fail (g_async_queue_length_unlocked (pool->queue) ==
598 pool->immediate = TRUE;
599 for (i = 0; i < pool->num_threads; i++)
600 g_async_queue_push_unlocked (pool->queue, GUINT_TO_POINTER (1));
604 * g_thread_pool_set_max_unused_threads:
605 * @max_threads: maximal number of unused threads
607 * Sets the maximal number of unused threads to @max_threads. If
608 * @max_threads is -1, no limit is imposed on the number of unused
612 g_thread_pool_set_max_unused_threads (gint max_threads)
614 g_return_if_fail (max_threads >= -1);
616 G_LOCK (unused_threads);
618 max_unused_threads = max_threads;
620 if (max_unused_threads < unused_threads && max_unused_threads != -1)
624 g_async_queue_lock (unused_thread_queue);
625 for (i = unused_threads - max_unused_threads; i > 0; i--)
626 g_async_queue_push_unlocked (unused_thread_queue,
627 stop_this_thread_marker);
628 g_async_queue_unlock (unused_thread_queue);
631 G_UNLOCK (unused_threads);
635 * g_thread_pool_get_max_unused_threads:
637 * Returns the maximal allowed number of unused threads.
639 * Return value: the maximal number of unused threads
642 g_thread_pool_get_max_unused_threads (void)
646 G_LOCK (unused_threads);
647 retval = max_unused_threads;
648 G_UNLOCK (unused_threads);
654 * g_thread_pool_get_num_unused_threads:
656 * Returns the number of currently unused threads.
658 * Return value: the number of currently unused threads
660 guint g_thread_pool_get_num_unused_threads (void)
664 G_LOCK (unused_threads);
665 retval = unused_threads;
666 G_UNLOCK (unused_threads);
672 * g_thread_pool_stop_unused_threads:
674 * Stops all currently unused threads. This does not change the
675 * maximal number of unused threads. This function can be used to
676 * regularly stop all unused threads e.g. from g_timeout_add().
678 void g_thread_pool_stop_unused_threads (void)
680 guint oldval = g_thread_pool_get_max_unused_threads ();
681 g_thread_pool_set_max_unused_threads (0);
682 g_thread_pool_set_max_unused_threads (oldval);
685 #define __G_THREADPOOL_C__
686 #include "galiasdef.c"