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, depending on their priority */
48 static GAsyncQueue *unused_thread_queue[G_THREAD_PRIORITY_URGENT + 1][2];
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 =
76 !pool->pool.exclusive && pool->pool.stack_size == 0;
77 gint len = g_async_queue_length_unlocked (pool->queue);
79 if (g_thread_should_run (pool, len))
83 /* This thread is actually not needed here, but it waits
84 * for some time anyway. If during that time a new
85 * request arrives, this saves process
86 * swicthes. Otherwise the thread will go to the global
89 g_get_current_time (&end_time);
90 end_time.tv_usec += G_USEC_PER_SEC / 2; /* Halv a second */
91 if (end_time.tv_usec >= G_USEC_PER_SEC)
93 end_time.tv_usec -= G_USEC_PER_SEC;
97 task = g_async_queue_timed_pop_unlocked (pool->queue, &end_time);
101 task = g_async_queue_pop_unlocked (pool->queue);
107 if (pool->num_threads > pool->max_threads &&
108 pool->max_threads != -1)
109 /* We are in fact a superfluous threads, so we go to
110 * the global pool and just hand the data further to
111 * the next one waiting in the queue */
113 g_async_queue_push_unlocked (pool->queue, task);
114 goto_global_pool = TRUE;
116 else if (pool->running || !pool->immediate)
118 g_async_queue_unlock (pool->queue);
119 pool->pool.thread_func (task, pool->pool.user_data);
120 g_async_queue_lock (pool->queue);
123 len = g_async_queue_length_unlocked (pool->queue);
126 if (!g_thread_should_run (pool, len))
128 g_cond_broadcast (inform_cond);
129 goto_global_pool = TRUE;
133 /* At this pool there are no threads waiting, but tasks are. */
134 goto_global_pool = FALSE;
136 else if (len == 0 && !watcher && !pool->pool.exclusive)
138 /* Here neither threads nor tasks are queued and we didn't
139 * just return from a timed wait. We now wait for a limited
140 * time at this pool for new tasks to avoid costly context
142 goto_global_pool = FALSE;
147 if (goto_global_pool)
149 GAsyncQueue *unused_queue =
150 unused_thread_queue[pool->pool.priority][pool->pool.bound ? 1 : 0];
153 if (!pool->running && !pool->waiting)
155 if (pool->num_threads == 0)
157 g_async_queue_unlock (pool->queue);
158 g_thread_pool_free_internal (pool);
160 else if (len == - pool->num_threads)
162 g_thread_pool_wakeup_and_stop_all (pool);
163 g_async_queue_unlock (pool->queue);
167 g_async_queue_unlock (pool->queue);
169 g_async_queue_lock (unused_queue);
171 G_LOCK (unused_threads);
172 if ((unused_threads >= max_unused_threads &&
173 max_unused_threads != -1) || pool->pool.stack_size != 0)
175 G_UNLOCK (unused_threads);
176 g_async_queue_unlock (unused_queue);
177 /* Stop this thread */
181 G_UNLOCK (unused_threads);
183 pool = g_async_queue_pop_unlocked (unused_queue);
185 G_LOCK (unused_threads);
187 G_UNLOCK (unused_threads);
189 g_async_queue_unlock (unused_queue);
191 if (pool == stop_this_thread_marker)
192 /* Stop this thread */
195 g_async_queue_lock (pool->queue);
197 /* pool->num_threads++ is not done here, but in
198 * g_thread_pool_start_thread to make the new started thread
199 * known to the pool, before itself can do it. */
206 g_thread_pool_start_thread (GRealThreadPool *pool,
209 gboolean success = FALSE;
210 GThreadPriority priority = pool->pool.priority;
211 guint bound = pool->pool.bound ? 1 : 0;
212 GAsyncQueue *queue = unused_thread_queue[priority][bound];
214 if (pool->num_threads >= pool->max_threads && pool->max_threads != -1)
215 /* Enough threads are already running */
218 g_async_queue_lock (queue);
220 if (g_async_queue_length_unlocked (queue) < 0)
222 /* First we try a thread with the right priority */
223 g_async_queue_push_unlocked (queue, pool);
227 g_async_queue_unlock (queue);
229 /* We will not search for threads with other priorities, because changing
230 * priority is quite unportable */
234 GError *local_error = NULL;
235 /* No thread was found, we have to start a new one */
236 g_thread_create (g_thread_pool_thread_proxy, pool,
237 pool->pool.stack_size, FALSE,
238 bound, priority, &local_error);
242 g_propagate_error (error, local_error);
247 /* See comment in g_thread_pool_thread_proxy as to why this is done
248 * here and not there */
254 * @thread_func: a function to execute in the threads of the new thread pool
255 * @max_threads: the maximal number of threads to execute concurrently in
256 * the new thread pool, -1 means no limit
257 * @stack_size: the stack size for the threads of the new thread pool,
258 * 0 means using the standard
259 * @bound: should the threads of the new thread pool be bound?
260 * @priority: a priority for the threads of the new thread pool
261 * @exclusive: should this thread pool be exclusive?
262 * @user_data: user data that is handed over to @thread_func every time it
264 * @error: return location for error
266 * This function creates a new thread pool. All threads created within
267 * this thread pool will have the priority @priority and the stack
268 * size @stack_size and will be bound if and only if @bound is
271 * Whenever you call g_thread_pool_push(), either a new thread is
272 * created or an unused one is reused. At most @max_threads threads
273 * are running concurrently for this thread pool. @max_threads = -1
274 * allows unlimited threads to be created for this thread pool. The
275 * newly created or reused thread now executes the function
276 * @thread_func with the two arguments. The first one is the parameter
277 * to g_thread_pool_push() and the second one is @user_data.
279 * The parameter @exclusive determines, whether the thread pool owns
280 * all threads exclusive or whether the threads are shared
281 * globally. If @exclusive is @TRUE, @max_threads threads are started
282 * immediately and they will run exclusively for this thread pool until
283 * it is destroyed by g_thread_pool_free(). If @exclusive is @FALSE,
284 * threads are created, when needed and shared between all
285 * non-exclusive thread pools. This implies that @max_threads may not
286 * be -1 for exclusive thread pools.
288 * Note, that only threads from a thread pool with a @stack_size of 0
289 * (which means using the standard stack size) will be globally
290 * reused. Threads from a thread pool with a non-zero stack size will
291 * stay only in this thread pool until it is freed and can thus not be
292 * controlled by the g_thread_pool_set_unused_threads() function.
294 * @error can be NULL to ignore errors, or non-NULL to report
295 * errors. An error can only occur, when @exclusive is set to @TRUE and
296 * not all @max_threads threads could be created.
298 * Return value: the new #GThreadPool
301 g_thread_pool_new (GFunc thread_func,
305 GThreadPriority priority,
310 GRealThreadPool *retval;
311 G_LOCK_DEFINE_STATIC (init);
313 g_return_val_if_fail (thread_func, NULL);
314 g_return_val_if_fail (!exclusive || max_threads != -1, NULL);
315 g_return_val_if_fail (max_threads >= -1, NULL);
316 g_return_val_if_fail (g_thread_supported (), NULL);
318 retval = g_new (GRealThreadPool, 1);
320 retval->pool.thread_func = thread_func;
321 retval->pool.stack_size = stack_size;
322 retval->pool.bound = bound;
323 retval->pool.priority = priority;
324 retval->pool.exclusive = exclusive;
325 retval->pool.user_data = user_data;
326 retval->queue = g_async_queue_new ();
327 retval->max_threads = max_threads;
328 retval->num_threads = 0;
329 retval->running = TRUE;
335 inform_mutex = g_mutex_new ();
336 inform_cond = g_cond_new ();
337 for (priority = G_THREAD_PRIORITY_LOW;
338 priority < G_THREAD_PRIORITY_URGENT + 1; priority++)
340 unused_thread_queue[priority][0] = g_async_queue_new ();
341 unused_thread_queue[priority][1] = g_async_queue_new ();
347 if (retval->pool.exclusive)
349 g_async_queue_lock (retval->queue);
351 while (retval->num_threads < retval->max_threads)
353 GError *local_error = NULL;
354 g_thread_pool_start_thread (retval, &local_error);
357 g_propagate_error (error, local_error);
362 g_async_queue_unlock (retval->queue);
365 return (GThreadPool*) retval;
369 * g_thread_pool_push:
370 * @pool: a #GThreadPool
371 * @data: a new task for @pool
372 * @error: return location for error
374 * Inserts @data into the list of tasks to be executed by @pool. When
375 * the number of currently running threads is lower than the maximal
376 * allowed number of threads, a new thread is started (or reused) with
377 * the properties given to g_thread_pool_new (). Otherwise @data stays
378 * in the queue until a thread in this pool finishes its previous task
379 * and processes @data.
381 * @error can be NULL to ignore errors, or non-NULL to report
382 * errors. An error can only occur, when a new thread couldn't be
383 * created. In that case @data is simply appended to the queue of work
387 g_thread_pool_push (GThreadPool *pool,
391 GRealThreadPool *real = (GRealThreadPool*) pool;
393 g_return_if_fail (real);
395 g_async_queue_lock (real->queue);
399 g_async_queue_unlock (real->queue);
400 g_return_if_fail (real->running);
403 if (g_async_queue_length_unlocked (real->queue) >= 0)
404 /* No thread is waiting in the queue */
405 g_thread_pool_start_thread (real, error);
407 g_async_queue_push_unlocked (real->queue, data);
408 g_async_queue_unlock (real->queue);
412 * g_thread_pool_set_max_threads:
413 * @pool: a #GThreadPool
414 * @max_threads: a new maximal number of threads for @pool
415 * @error: return location for error
417 * Sets the maximal allowed number of threads for @pool. A value of -1
418 * means, that the maximal number of threads is unlimited.
420 * Setting @max_threads to 0 means stopping all work for @pool. It is
421 * effectively frozen until @max_threads is set to a non-zero value
424 * A thread is never terminated while calling @thread_func, as
425 * supplied by g_thread_pool_new (). Instead the maximal number of
426 * threads only has effect for the allocation of new threads in
427 * g_thread_pool_push (). A new thread is allocated, whenever the
428 * number of currently running threads in @pool is smaller than the
431 * @error can be NULL to ignore errors, or non-NULL to report
432 * errors. An error can only occur, when a new thread couldn't be
436 g_thread_pool_set_max_threads (GThreadPool *pool,
440 GRealThreadPool *real = (GRealThreadPool*) pool;
443 g_return_if_fail (real);
444 g_return_if_fail (real->running);
445 g_return_if_fail (!real->pool.exclusive || max_threads != -1);
446 g_return_if_fail (max_threads >= -1);
448 g_async_queue_lock (real->queue);
450 real->max_threads = max_threads;
453 to_start = real->max_threads - real->num_threads;
455 to_start = g_async_queue_length_unlocked (real->queue);
457 for ( ; to_start > 0; to_start--)
459 GError *local_error = NULL;
460 g_thread_pool_start_thread (real, &local_error);
463 g_propagate_error (error, local_error);
468 g_async_queue_unlock (real->queue);
472 * g_thread_pool_get_max_threads:
473 * @pool: a #GThreadPool
475 * Returns the maximal number of threads for @pool.
477 * Return value: the maximal number of threads
480 g_thread_pool_get_max_threads (GThreadPool *pool)
482 GRealThreadPool *real = (GRealThreadPool*) pool;
485 g_return_val_if_fail (real, 0);
486 g_return_val_if_fail (real->running, 0);
488 g_async_queue_lock (real->queue);
490 retval = real->max_threads;
492 g_async_queue_unlock (real->queue);
498 * g_thread_pool_get_num_threads:
499 * @pool: a #GThreadPool
501 * Returns the number of threads currently running in @pool.
503 * Return value: the number of threads currently running
506 g_thread_pool_get_num_threads (GThreadPool *pool)
508 GRealThreadPool *real = (GRealThreadPool*) pool;
511 g_return_val_if_fail (real, 0);
512 g_return_val_if_fail (real->running, 0);
514 g_async_queue_lock (real->queue);
516 retval = real->num_threads;
518 g_async_queue_unlock (real->queue);
524 * g_thread_pool_unprocessed:
525 * @pool: a #GThreadPool
527 * Returns the number of tasks still unprocessed in @pool.
529 * Return value: the number of unprocessed tasks
532 g_thread_pool_unprocessed (GThreadPool *pool)
534 GRealThreadPool *real = (GRealThreadPool*) pool;
537 g_return_val_if_fail (real, 0);
538 g_return_val_if_fail (real->running, 0);
540 unprocessed = g_async_queue_length (real->queue);
542 return MAX (unprocessed, 0);
546 * g_thread_pool_free:
547 * @pool: a #GThreadPool
548 * @immediate: should @pool shut down immediately?
549 * @wait: should the function wait for all tasks to be finished?
551 * Frees all resources allocated for @pool.
553 * If @immediate is #TRUE, no new task is processed for
554 * @pool. Otherwise @pool is not freed before the last task is
555 * processed. Note however, that no thread of this pool is
556 * interrupted, while processing a task. Instead at least all still
557 * running threads can finish their tasks before the @pool is freed.
559 * If @wait is #TRUE, the functions does not return before all tasks
560 * to be processed (dependent on @immediate, whether all or only the
561 * currently running) are ready. Otherwise the function returns immediately.
563 * After calling this function @pool must not be used anymore.
566 g_thread_pool_free (GThreadPool *pool,
570 GRealThreadPool *real = (GRealThreadPool*) pool;
572 g_return_if_fail (real);
573 g_return_if_fail (real->running);
574 /* It there's no thread allowed here, there is not much sense in
575 * not stopping this pool immediately, when it's not empty */
576 g_return_if_fail (immediate || real->max_threads != 0 ||
577 g_async_queue_length (real->queue) == 0);
579 g_async_queue_lock (real->queue);
581 real->running = FALSE;
582 real->immediate = immediate;
583 real->waiting = wait;
587 g_mutex_lock (inform_mutex);
588 while (g_async_queue_length_unlocked (real->queue) != -real->num_threads)
590 g_async_queue_unlock (real->queue);
591 g_cond_wait (inform_cond, inform_mutex);
592 g_async_queue_lock (real->queue);
594 g_mutex_unlock (inform_mutex);
597 if (g_async_queue_length_unlocked (real->queue) == -real->num_threads)
599 /* No thread is currently doing something (and nothing is left
600 * to process in the queue) */
601 if (real->num_threads == 0) /* No threads left, we clean up */
603 g_async_queue_unlock (real->queue);
604 g_thread_pool_free_internal (real);
608 g_thread_pool_wakeup_and_stop_all (real);
611 real->waiting = FALSE; /* The last thread should cleanup the pool */
612 g_async_queue_unlock (real->queue);
616 g_thread_pool_free_internal (GRealThreadPool* pool)
618 g_return_if_fail (pool);
619 g_return_if_fail (!pool->running);
620 g_return_if_fail (pool->num_threads == 0);
622 g_async_queue_unref (pool->queue);
628 g_thread_pool_wakeup_and_stop_all (GRealThreadPool* pool)
632 g_return_if_fail (pool);
633 g_return_if_fail (!pool->running);
634 g_return_if_fail (pool->num_threads != 0);
635 g_return_if_fail (g_async_queue_length_unlocked (pool->queue) ==
638 pool->immediate = TRUE;
639 for (i = 0; i < pool->num_threads; i++)
640 g_async_queue_push_unlocked (pool->queue, GUINT_TO_POINTER (1));
644 * g_thread_pool_set_max_unused_threads:
645 * @max_threads: maximal number of unused threads
647 * Sets the maximal number of unused threads to @max_threads. If
648 * @max_threads is -1, no limit is imposed on the number of unused
652 g_thread_pool_set_max_unused_threads (gint max_threads)
654 g_return_if_fail (max_threads >= -1);
656 G_LOCK (unused_threads);
658 max_unused_threads = max_threads;
660 if (max_unused_threads < unused_threads && max_unused_threads != -1)
662 guint close_down_num = unused_threads - max_unused_threads;
664 while (close_down_num > 0)
666 GThreadPriority priority;
669 guint old_close_down_num = close_down_num;
670 for (priority = G_THREAD_PRIORITY_LOW;
671 priority < G_THREAD_PRIORITY_URGENT + 1 && close_down_num > 0;
674 for (bound = 0; bound < 2; bound++)
676 GAsyncQueue *queue = unused_thread_queue[priority][bound];
677 g_async_queue_lock (queue);
679 if (g_async_queue_length_unlocked (queue) < 0)
681 g_async_queue_push_unlocked (queue,
682 stop_this_thread_marker);
686 g_async_queue_unlock (queue);
690 /* Just to make sure, there are no counting problems */
691 g_assert (old_close_down_num != close_down_num);
695 G_UNLOCK (unused_threads);
699 * g_thread_pool_get_max_unused_threads:
701 * Returns the maximal allowed number of unused threads.
703 * Return value: the maximal number of unused threads
706 g_thread_pool_get_max_unused_threads (void)
710 G_LOCK (unused_threads);
711 retval = max_unused_threads;
712 G_UNLOCK (unused_threads);
718 * g_thread_pool_get_num_unused_threads:
720 * Returns the number of currently unused threads.
722 * Return value: the number of currently unused threads
724 guint g_thread_pool_get_num_unused_threads (void)
728 G_LOCK (unused_threads);
729 retval = unused_threads;
730 G_UNLOCK (unused_threads);
736 * g_thread_pool_stop_unused_threads:
738 * Stops all currently unused threads. This does not change the
739 * maximal number of unused threads. This function can be used to
740 * regularly stop all unused threads e.g. from g_timeout_add().
742 void g_thread_pool_stop_unused_threads (void)
744 guint oldval = g_thread_pool_get_max_unused_threads ();
745 g_thread_pool_set_max_unused_threads (0);
746 g_thread_pool_set_max_unused_threads (oldval);