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.
29 typedef struct _GRealThreadPool GRealThreadPool;
31 struct _GRealThreadPool
42 /* The following is just an address to mark the stop order for a
43 * thread, it could be any address (as long, as it isn't a valid
44 * GThreadPool address) */
45 static const gpointer stop_this_thread_marker = (gpointer) &g_thread_pool_new;
47 /* Here all unused threads are waiting */
48 static GAsyncQueue *unused_thread_queue;
49 static gint unused_threads = 0;
50 static gint max_unused_threads = 0;
51 G_LOCK_DEFINE_STATIC (unused_threads);
53 static GMutex *inform_mutex = NULL;
54 static GCond *inform_cond = NULL;
56 static void g_thread_pool_free_internal (GRealThreadPool* pool);
57 static gpointer g_thread_pool_thread_proxy (gpointer data);
58 static void g_thread_pool_start_thread (GRealThreadPool* pool,
60 static void g_thread_pool_wakeup_and_stop_all (GRealThreadPool* pool);
62 #define g_thread_should_run(pool, len) \
63 ((pool)->running || (!(pool)->immediate && (len) > 0))
66 g_thread_pool_thread_proxy (gpointer data)
68 GRealThreadPool *pool = data;
69 gboolean watcher = FALSE;
71 g_async_queue_lock (pool->queue);
75 gboolean goto_global_pool = !pool->pool.exclusive;
76 gint len = g_async_queue_length_unlocked (pool->queue);
78 if (g_thread_should_run (pool, len))
82 /* This thread is actually not needed here, but it waits
83 * for some time anyway. If during that time a new
84 * request arrives, this saves process
85 * swicthes. Otherwise the thread will go to the global
88 g_get_current_time (&end_time);
89 g_time_val_add (&end_time, G_USEC_PER_SEC / 2); /* 1/2 second */
90 task = g_async_queue_timed_pop_unlocked (pool->queue, &end_time);
93 task = g_async_queue_pop_unlocked (pool->queue);
98 if (pool->num_threads > pool->max_threads &&
99 pool->max_threads != -1)
100 /* We are in fact a superfluous threads, so we go to
101 * the global pool and just hand the data further to
102 * the next one waiting in the queue */
104 g_async_queue_push_unlocked (pool->queue, task);
105 goto_global_pool = TRUE;
107 else if (pool->running || !pool->immediate)
109 g_async_queue_unlock (pool->queue);
110 pool->pool.func (task, pool->pool.user_data);
111 g_async_queue_lock (pool->queue);
114 len = g_async_queue_length_unlocked (pool->queue);
117 if (!g_thread_should_run (pool, len))
119 g_cond_broadcast (inform_cond);
120 goto_global_pool = TRUE;
124 /* At this pool there are no threads waiting, but tasks are. */
125 goto_global_pool = FALSE;
127 else if (len == 0 && !watcher && !pool->pool.exclusive)
129 /* Here neither threads nor tasks are queued and we didn't
130 * just return from a timed wait. We now wait for a limited
131 * time at this pool for new tasks to avoid costly context
133 goto_global_pool = FALSE;
137 if (goto_global_pool)
141 if (!pool->running && !pool->waiting)
143 if (pool->num_threads == 0)
145 g_async_queue_unlock (pool->queue);
146 g_thread_pool_free_internal (pool);
150 if (len == - pool->num_threads)
151 g_thread_pool_wakeup_and_stop_all (pool);
153 g_async_queue_unlock (pool->queue);
157 g_async_queue_unlock (pool->queue);
159 g_async_queue_lock (unused_thread_queue);
161 G_LOCK (unused_threads);
162 if ((unused_threads >= max_unused_threads &&
163 max_unused_threads != -1))
165 G_UNLOCK (unused_threads);
166 g_async_queue_unlock (unused_thread_queue);
167 /* Stop this thread */
171 G_UNLOCK (unused_threads);
173 pool = g_async_queue_pop_unlocked (unused_thread_queue);
175 G_LOCK (unused_threads);
177 G_UNLOCK (unused_threads);
179 g_async_queue_unlock (unused_thread_queue);
181 if (pool == stop_this_thread_marker)
182 /* Stop this thread */
185 g_async_queue_lock (pool->queue);
187 /* pool->num_threads++ is not done here, but in
188 * g_thread_pool_start_thread to make the new started thread
189 * known to the pool, before itself can do it. */
196 g_thread_pool_start_thread (GRealThreadPool *pool,
199 gboolean success = FALSE;
201 if (pool->num_threads >= pool->max_threads && pool->max_threads != -1)
202 /* Enough threads are already running */
205 g_async_queue_lock (unused_thread_queue);
207 if (g_async_queue_length_unlocked (unused_thread_queue) < 0)
209 g_async_queue_push_unlocked (unused_thread_queue, pool);
213 g_async_queue_unlock (unused_thread_queue);
217 GError *local_error = NULL;
218 /* No thread was found, we have to start a new one */
219 g_thread_create (g_thread_pool_thread_proxy, pool, FALSE, &local_error);
223 g_propagate_error (error, local_error);
228 /* See comment in g_thread_pool_thread_proxy as to why this is done
229 * here and not there */
235 * @func: a function to execute in the threads of the new thread pool
236 * @user_data: user data that is handed over to @func every time it
238 * @max_threads: the maximal number of threads to execute concurrently in
239 * the new thread pool, -1 means no limit
240 * @exclusive: should this thread pool be exclusive?
241 * @error: return location for error
243 * This function creates a new thread pool.
245 * Whenever you call g_thread_pool_push(), either a new thread is
246 * created or an unused one is reused. At most @max_threads threads
247 * are running concurrently for this thread pool. @max_threads = -1
248 * allows unlimited threads to be created for this thread pool. The
249 * newly created or reused thread now executes the function @func with
250 * the two arguments. The first one is the parameter to
251 * g_thread_pool_push() and the second one is @user_data.
253 * The parameter @exclusive determines, whether the thread pool owns
254 * all threads exclusive or whether the threads are shared
255 * globally. If @exclusive is %TRUE, @max_threads threads are started
256 * immediately and they will run exclusively for this thread pool until
257 * it is destroyed by g_thread_pool_free(). If @exclusive is %FALSE,
258 * threads are created, when needed and shared between all
259 * non-exclusive thread pools. This implies that @max_threads may not
260 * be -1 for exclusive thread pools.
262 * @error can be %NULL to ignore errors, or non-%NULL to report
263 * errors. An error can only occur when @exclusive is set to %TRUE and
264 * not all @max_threads threads could be created.
266 * Return value: the new #GThreadPool
269 g_thread_pool_new (GFunc func,
275 GRealThreadPool *retval;
276 G_LOCK_DEFINE_STATIC (init);
278 g_return_val_if_fail (func, NULL);
279 g_return_val_if_fail (!exclusive || max_threads != -1, NULL);
280 g_return_val_if_fail (max_threads >= -1, NULL);
281 g_return_val_if_fail (g_thread_supported (), NULL);
283 retval = g_new (GRealThreadPool, 1);
285 retval->pool.func = func;
286 retval->pool.user_data = user_data;
287 retval->pool.exclusive = exclusive;
288 retval->queue = g_async_queue_new ();
289 retval->max_threads = max_threads;
290 retval->num_threads = 0;
291 retval->running = TRUE;
297 inform_mutex = g_mutex_new ();
298 inform_cond = g_cond_new ();
299 unused_thread_queue = g_async_queue_new ();
304 if (retval->pool.exclusive)
306 g_async_queue_lock (retval->queue);
308 while (retval->num_threads < retval->max_threads)
310 GError *local_error = NULL;
311 g_thread_pool_start_thread (retval, &local_error);
314 g_propagate_error (error, local_error);
319 g_async_queue_unlock (retval->queue);
322 return (GThreadPool*) retval;
326 * g_thread_pool_push:
327 * @pool: a #GThreadPool
328 * @data: a new task for @pool
329 * @error: return location for error
331 * Inserts @data into the list of tasks to be executed by @pool. When
332 * the number of currently running threads is lower than the maximal
333 * allowed number of threads, a new thread is started (or reused) with
334 * the properties given to g_thread_pool_new (). Otherwise @data stays
335 * in the queue until a thread in this pool finishes its previous task
336 * and processes @data.
338 * @error can be %NULL to ignore errors, or non-%NULL to report
339 * errors. An error can only occur when a new thread couldn't be
340 * created. In that case @data is simply appended to the queue of work
344 g_thread_pool_push (GThreadPool *pool,
348 GRealThreadPool *real = (GRealThreadPool*) pool;
350 g_return_if_fail (real);
352 g_async_queue_lock (real->queue);
356 g_async_queue_unlock (real->queue);
357 g_return_if_fail (real->running);
360 if (g_async_queue_length_unlocked (real->queue) >= 0)
361 /* No thread is waiting in the queue */
362 g_thread_pool_start_thread (real, error);
364 g_async_queue_push_unlocked (real->queue, data);
365 g_async_queue_unlock (real->queue);
369 * g_thread_pool_set_max_threads:
370 * @pool: a #GThreadPool
371 * @max_threads: a new maximal number of threads for @pool
372 * @error: return location for error
374 * Sets the maximal allowed number of threads for @pool. A value of -1
375 * means, that the maximal number of threads is unlimited.
377 * Setting @max_threads to 0 means stopping all work for @pool. It is
378 * effectively frozen until @max_threads is set to a non-zero value
381 * A thread is never terminated while calling @func, as supplied by
382 * g_thread_pool_new (). Instead the maximal number of threads only
383 * has effect for the allocation of new threads in g_thread_pool_push().
384 * A new thread is allocated, whenever the number of currently
385 * running threads in @pool is smaller than the maximal number.
387 * @error can be %NULL to ignore errors, or non-%NULL to report
388 * errors. An error can only occur when a new thread couldn't be
392 g_thread_pool_set_max_threads (GThreadPool *pool,
396 GRealThreadPool *real = (GRealThreadPool*) pool;
399 g_return_if_fail (real);
400 g_return_if_fail (real->running);
401 g_return_if_fail (!real->pool.exclusive || max_threads != -1);
402 g_return_if_fail (max_threads >= -1);
404 g_async_queue_lock (real->queue);
406 real->max_threads = max_threads;
409 to_start = real->max_threads - real->num_threads;
411 to_start = g_async_queue_length_unlocked (real->queue);
413 for ( ; to_start > 0; to_start--)
415 GError *local_error = NULL;
416 g_thread_pool_start_thread (real, &local_error);
419 g_propagate_error (error, local_error);
424 g_async_queue_unlock (real->queue);
428 * g_thread_pool_get_max_threads:
429 * @pool: a #GThreadPool
431 * Returns the maximal number of threads for @pool.
433 * Return value: the maximal number of threads
436 g_thread_pool_get_max_threads (GThreadPool *pool)
438 GRealThreadPool *real = (GRealThreadPool*) pool;
441 g_return_val_if_fail (real, 0);
442 g_return_val_if_fail (real->running, 0);
444 g_async_queue_lock (real->queue);
446 retval = real->max_threads;
448 g_async_queue_unlock (real->queue);
454 * g_thread_pool_get_num_threads:
455 * @pool: a #GThreadPool
457 * Returns the number of threads currently running in @pool.
459 * Return value: the number of threads currently running
462 g_thread_pool_get_num_threads (GThreadPool *pool)
464 GRealThreadPool *real = (GRealThreadPool*) pool;
467 g_return_val_if_fail (real, 0);
468 g_return_val_if_fail (real->running, 0);
470 g_async_queue_lock (real->queue);
472 retval = real->num_threads;
474 g_async_queue_unlock (real->queue);
480 * g_thread_pool_unprocessed:
481 * @pool: a #GThreadPool
483 * Returns the number of tasks still unprocessed in @pool.
485 * Return value: the number of unprocessed tasks
488 g_thread_pool_unprocessed (GThreadPool *pool)
490 GRealThreadPool *real = (GRealThreadPool*) pool;
493 g_return_val_if_fail (real, 0);
494 g_return_val_if_fail (real->running, 0);
496 unprocessed = g_async_queue_length (real->queue);
498 return MAX (unprocessed, 0);
502 * g_thread_pool_free:
503 * @pool: a #GThreadPool
504 * @immediate: should @pool shut down immediately?
505 * @wait: should the function wait for all tasks to be finished?
507 * Frees all resources allocated for @pool.
509 * If @immediate is %TRUE, no new task is processed for
510 * @pool. Otherwise @pool is not freed before the last task is
511 * processed. Note however, that no thread of this pool is
512 * interrupted, while processing a task. Instead at least all still
513 * running threads can finish their tasks before the @pool is freed.
515 * If @wait is %TRUE, the functions does not return before all tasks
516 * to be processed (dependent on @immediate, whether all or only the
517 * currently running) are ready. Otherwise the function returns immediately.
519 * After calling this function @pool must not be used anymore.
522 g_thread_pool_free (GThreadPool *pool,
526 GRealThreadPool *real = (GRealThreadPool*) pool;
528 g_return_if_fail (real);
529 g_return_if_fail (real->running);
530 /* It there's no thread allowed here, there is not much sense in
531 * not stopping this pool immediately, when it's not empty */
532 g_return_if_fail (immediate || real->max_threads != 0 ||
533 g_async_queue_length (real->queue) == 0);
535 g_async_queue_lock (real->queue);
537 real->running = FALSE;
538 real->immediate = immediate;
539 real->waiting = wait;
543 g_mutex_lock (inform_mutex);
544 while (g_async_queue_length_unlocked (real->queue) != -real->num_threads)
546 g_async_queue_unlock (real->queue);
547 g_cond_wait (inform_cond, inform_mutex);
548 g_async_queue_lock (real->queue);
550 g_mutex_unlock (inform_mutex);
553 if (g_async_queue_length_unlocked (real->queue) == -real->num_threads)
555 /* No thread is currently doing something (and nothing is left
556 * to process in the queue) */
557 if (real->num_threads == 0) /* No threads left, we clean up */
559 g_async_queue_unlock (real->queue);
560 g_thread_pool_free_internal (real);
564 g_thread_pool_wakeup_and_stop_all (real);
567 real->waiting = FALSE; /* The last thread should cleanup the pool */
568 g_async_queue_unlock (real->queue);
572 g_thread_pool_free_internal (GRealThreadPool* pool)
574 g_return_if_fail (pool);
575 g_return_if_fail (!pool->running);
576 g_return_if_fail (pool->num_threads == 0);
578 g_async_queue_unref (pool->queue);
584 g_thread_pool_wakeup_and_stop_all (GRealThreadPool* pool)
588 g_return_if_fail (pool);
589 g_return_if_fail (!pool->running);
590 g_return_if_fail (pool->num_threads != 0);
591 g_return_if_fail (g_async_queue_length_unlocked (pool->queue) ==
594 pool->immediate = TRUE;
595 for (i = 0; i < pool->num_threads; i++)
596 g_async_queue_push_unlocked (pool->queue, GUINT_TO_POINTER (1));
600 * g_thread_pool_set_max_unused_threads:
601 * @max_threads: maximal number of unused threads
603 * Sets the maximal number of unused threads to @max_threads. If
604 * @max_threads is -1, no limit is imposed on the number of unused
608 g_thread_pool_set_max_unused_threads (gint max_threads)
610 g_return_if_fail (max_threads >= -1);
612 G_LOCK (unused_threads);
614 max_unused_threads = max_threads;
616 if (max_unused_threads < unused_threads && max_unused_threads != -1)
620 g_async_queue_lock (unused_thread_queue);
621 for (i = unused_threads - max_unused_threads; i > 0; i--)
622 g_async_queue_push_unlocked (unused_thread_queue,
623 stop_this_thread_marker);
624 g_async_queue_unlock (unused_thread_queue);
627 G_UNLOCK (unused_threads);
631 * g_thread_pool_get_max_unused_threads:
633 * Returns the maximal allowed number of unused threads.
635 * Return value: the maximal number of unused threads
638 g_thread_pool_get_max_unused_threads (void)
642 G_LOCK (unused_threads);
643 retval = max_unused_threads;
644 G_UNLOCK (unused_threads);
650 * g_thread_pool_get_num_unused_threads:
652 * Returns the number of currently unused threads.
654 * Return value: the number of currently unused threads
656 guint g_thread_pool_get_num_unused_threads (void)
660 G_LOCK (unused_threads);
661 retval = unused_threads;
662 G_UNLOCK (unused_threads);
668 * g_thread_pool_stop_unused_threads:
670 * Stops all currently unused threads. This does not change the
671 * maximal number of unused threads. This function can be used to
672 * regularly stop all unused threads e.g. from g_timeout_add().
674 void g_thread_pool_stop_unused_threads (void)
676 guint oldval = g_thread_pool_get_max_unused_threads ();
677 g_thread_pool_set_max_unused_threads (0);
678 g_thread_pool_set_max_unused_threads (oldval);