Imported Upstream version 0.27.1
[platform/upstream/pkg-config.git] / glib / glib / gthreadpool.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * GThreadPool: thread pool implementation.
5  * Copyright (C) 2000 Sebastian Wilhelmi; University of Karlsruhe
6  *
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.
11  *
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.
16  *
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.
21  */
22
23 /*
24  * MT safe
25  */
26
27 #include "config.h"
28
29 #include "gthreadpool.h"
30
31 #include "gasyncqueue.h"
32 #include "gasyncqueueprivate.h"
33 #include "gmain.h"
34 #include "gtestutils.h"
35 #include "gtimer.h"
36
37 /**
38  * SECTION:thread_pools
39  * @title: Thread Pools
40  * @short_description: pools of threads to execute work concurrently
41  * @see_also: #GThread
42  *
43  * Sometimes you wish to asynchronously fork out the execution of work
44  * and continue working in your own thread. If that will happen often,
45  * the overhead of starting and destroying a thread each time might be
46  * too high. In such cases reusing already started threads seems like a
47  * good idea. And it indeed is, but implementing this can be tedious
48  * and error-prone.
49  *
50  * Therefore GLib provides thread pools for your convenience. An added
51  * advantage is, that the threads can be shared between the different
52  * subsystems of your program, when they are using GLib.
53  *
54  * To create a new thread pool, you use g_thread_pool_new().
55  * It is destroyed by g_thread_pool_free().
56  *
57  * If you want to execute a certain task within a thread pool,
58  * you call g_thread_pool_push().
59  *
60  * To get the current number of running threads you call
61  * g_thread_pool_get_num_threads(). To get the number of still
62  * unprocessed tasks you call g_thread_pool_unprocessed(). To control
63  * the maximal number of threads for a thread pool, you use
64  * g_thread_pool_get_max_threads() and g_thread_pool_set_max_threads().
65  *
66  * Finally you can control the number of unused threads, that are kept
67  * alive by GLib for future use. The current number can be fetched with
68  * g_thread_pool_get_num_unused_threads(). The maximal number can be
69  * controlled by g_thread_pool_get_max_unused_threads() and
70  * g_thread_pool_set_max_unused_threads(). All currently unused threads
71  * can be stopped by calling g_thread_pool_stop_unused_threads().
72  */
73
74 #define DEBUG_MSG(x)
75 /* #define DEBUG_MSG(args) g_printerr args ; g_printerr ("\n");    */
76
77 typedef struct _GRealThreadPool GRealThreadPool;
78
79 /**
80  * GThreadPool:
81  * @func: the function to execute in the threads of this pool
82  * @user_data: the user data for the threads of this pool
83  * @exclusive: are all threads exclusive to this pool
84  *
85  * The #GThreadPool struct represents a thread pool. It has three
86  * public read-only members, but the underlying struct is bigger,
87  * so you must not copy this struct.
88  */
89 struct _GRealThreadPool
90 {
91   GThreadPool pool;
92   GAsyncQueue *queue;
93   GCond cond;
94   gint max_threads;
95   gint num_threads;
96   gboolean running;
97   gboolean immediate;
98   gboolean waiting;
99   GCompareDataFunc sort_func;
100   gpointer sort_user_data;
101 };
102
103 /* The following is just an address to mark the wakeup order for a
104  * thread, it could be any address (as long, as it isn't a valid
105  * GThreadPool address)
106  */
107 static const gpointer wakeup_thread_marker = (gpointer) &g_thread_pool_new;
108 static gint wakeup_thread_serial = 0;
109
110 /* Here all unused threads are waiting  */
111 static GAsyncQueue *unused_thread_queue = NULL;
112 static gint unused_threads = 0;
113 static gint max_unused_threads = 0;
114 static gint kill_unused_threads = 0;
115 static guint max_idle_time = 0;
116
117 static void             g_thread_pool_queue_push_unlocked (GRealThreadPool  *pool,
118                                                            gpointer          data);
119 static void             g_thread_pool_free_internal       (GRealThreadPool  *pool);
120 static gpointer         g_thread_pool_thread_proxy        (gpointer          data);
121 static gboolean         g_thread_pool_start_thread        (GRealThreadPool  *pool,
122                                                            GError          **error);
123 static void             g_thread_pool_wakeup_and_stop_all (GRealThreadPool  *pool);
124 static GRealThreadPool* g_thread_pool_wait_for_new_pool   (void);
125 static gpointer         g_thread_pool_wait_for_new_task   (GRealThreadPool  *pool);
126
127 static void
128 g_thread_pool_queue_push_unlocked (GRealThreadPool *pool,
129                                    gpointer         data)
130 {
131   if (pool->sort_func)
132     g_async_queue_push_sorted_unlocked (pool->queue,
133                                         data,
134                                         pool->sort_func,
135                                         pool->sort_user_data);
136   else
137     g_async_queue_push_unlocked (pool->queue, data);
138 }
139
140 static GRealThreadPool*
141 g_thread_pool_wait_for_new_pool (void)
142 {
143   GRealThreadPool *pool;
144   gint local_wakeup_thread_serial;
145   guint local_max_unused_threads;
146   gint local_max_idle_time;
147   gint last_wakeup_thread_serial;
148   gboolean have_relayed_thread_marker = FALSE;
149
150   local_max_unused_threads = g_atomic_int_get (&max_unused_threads);
151   local_max_idle_time = g_atomic_int_get (&max_idle_time);
152   last_wakeup_thread_serial = g_atomic_int_get (&wakeup_thread_serial);
153
154   g_atomic_int_inc (&unused_threads);
155
156   do
157     {
158       if (g_atomic_int_get (&unused_threads) >= local_max_unused_threads)
159         {
160           /* If this is a superfluous thread, stop it. */
161           pool = NULL;
162         }
163       else if (local_max_idle_time > 0)
164         {
165           /* If a maximal idle time is given, wait for the given time. */
166           DEBUG_MSG (("thread %p waiting in global pool for %f seconds.",
167                       g_thread_self (), local_max_idle_time / 1000.0));
168
169           pool = g_async_queue_timeout_pop (unused_thread_queue,
170                                             local_max_idle_time * 1000);
171         }
172       else
173         {
174           /* If no maximal idle time is given, wait indefinitely. */
175           DEBUG_MSG (("thread %p waiting in global pool.", g_thread_self ()));
176           pool = g_async_queue_pop (unused_thread_queue);
177         }
178
179       if (pool == wakeup_thread_marker)
180         {
181           local_wakeup_thread_serial = g_atomic_int_get (&wakeup_thread_serial);
182           if (last_wakeup_thread_serial == local_wakeup_thread_serial)
183             {
184               if (!have_relayed_thread_marker)
185               {
186                 /* If this wakeup marker has been received for
187                  * the second time, relay it.
188                  */
189                 DEBUG_MSG (("thread %p relaying wakeup message to "
190                             "waiting thread with lower serial.",
191                             g_thread_self ()));
192
193                 g_async_queue_push (unused_thread_queue, wakeup_thread_marker);
194                 have_relayed_thread_marker = TRUE;
195
196                 /* If a wakeup marker has been relayed, this thread
197                  * will get out of the way for 100 microseconds to
198                  * avoid receiving this marker again.
199                  */
200                 g_usleep (100);
201               }
202             }
203           else
204             {
205               if (g_atomic_int_add (&kill_unused_threads, -1) > 0)
206                 {
207                   pool = NULL;
208                   break;
209                 }
210
211               DEBUG_MSG (("thread %p updating to new limits.",
212                           g_thread_self ()));
213
214               local_max_unused_threads = g_atomic_int_get (&max_unused_threads);
215               local_max_idle_time = g_atomic_int_get (&max_idle_time);
216               last_wakeup_thread_serial = local_wakeup_thread_serial;
217
218               have_relayed_thread_marker = FALSE;
219             }
220         }
221     }
222   while (pool == wakeup_thread_marker);
223
224   g_atomic_int_add (&unused_threads, -1);
225
226   return pool;
227 }
228
229 static gpointer
230 g_thread_pool_wait_for_new_task (GRealThreadPool *pool)
231 {
232   gpointer task = NULL;
233
234   if (pool->running || (!pool->immediate &&
235                         g_async_queue_length_unlocked (pool->queue) > 0))
236     {
237       /* This thread pool is still active. */
238       if (pool->num_threads > pool->max_threads && pool->max_threads != -1)
239         {
240           /* This is a superfluous thread, so it goes to the global pool. */
241           DEBUG_MSG (("superfluous thread %p in pool %p.",
242                       g_thread_self (), pool));
243         }
244       else if (pool->pool.exclusive)
245         {
246           /* Exclusive threads stay attached to the pool. */
247           task = g_async_queue_pop_unlocked (pool->queue);
248
249           DEBUG_MSG (("thread %p in exclusive pool %p waits for task "
250                       "(%d running, %d unprocessed).",
251                       g_thread_self (), pool, pool->num_threads,
252                       g_async_queue_length_unlocked (pool->queue)));
253         }
254       else
255         {
256           /* A thread will wait for new tasks for at most 1/2
257            * second before going to the global pool.
258            */
259           DEBUG_MSG (("thread %p in pool %p waits for up to a 1/2 second for task "
260                       "(%d running, %d unprocessed).",
261                       g_thread_self (), pool, pool->num_threads,
262                       g_async_queue_length_unlocked (pool->queue)));
263
264           task = g_async_queue_timeout_pop_unlocked (pool->queue,
265                                                      G_USEC_PER_SEC / 2);
266         }
267     }
268   else
269     {
270       /* This thread pool is inactive, it will no longer process tasks. */
271       DEBUG_MSG (("pool %p not active, thread %p will go to global pool "
272                   "(running: %s, immediate: %s, len: %d).",
273                   pool, g_thread_self (),
274                   pool->running ? "true" : "false",
275                   pool->immediate ? "true" : "false",
276                   g_async_queue_length_unlocked (pool->queue)));
277     }
278
279   return task;
280 }
281
282
283 static gpointer
284 g_thread_pool_thread_proxy (gpointer data)
285 {
286   GRealThreadPool *pool;
287
288   pool = data;
289
290   DEBUG_MSG (("thread %p started for pool %p.", g_thread_self (), pool));
291
292   g_async_queue_lock (pool->queue);
293
294   while (TRUE)
295     {
296       gpointer task;
297
298       task = g_thread_pool_wait_for_new_task (pool);
299       if (task)
300         {
301           if (pool->running || !pool->immediate)
302             {
303               /* A task was received and the thread pool is active,
304                * so execute the function.
305                */
306               g_async_queue_unlock (pool->queue);
307               DEBUG_MSG (("thread %p in pool %p calling func.",
308                           g_thread_self (), pool));
309               pool->pool.func (task, pool->pool.user_data);
310               g_async_queue_lock (pool->queue);
311             }
312         }
313       else
314         {
315           /* No task was received, so this thread goes to the global pool. */
316           gboolean free_pool = FALSE;
317
318           DEBUG_MSG (("thread %p leaving pool %p for global pool.",
319                       g_thread_self (), pool));
320           pool->num_threads--;
321
322           if (!pool->running)
323             {
324               if (!pool->waiting)
325                 {
326                   if (pool->num_threads == 0)
327                     {
328                       /* If the pool is not running and no other
329                        * thread is waiting for this thread pool to
330                        * finish and this is the last thread of this
331                        * pool, free the pool.
332                        */
333                       free_pool = TRUE;
334                     }
335                   else
336                     {
337                       /* If the pool is not running and no other
338                        * thread is waiting for this thread pool to
339                        * finish and this is not the last thread of
340                        * this pool and there are no tasks left in the
341                        * queue, wakeup the remaining threads.
342                        */
343                       if (g_async_queue_length_unlocked (pool->queue) ==
344                           - pool->num_threads)
345                         g_thread_pool_wakeup_and_stop_all (pool);
346                     }
347                 }
348               else if (pool->immediate ||
349                        g_async_queue_length_unlocked (pool->queue) <= 0)
350                 {
351                   /* If the pool is not running and another thread is
352                    * waiting for this thread pool to finish and there
353                    * are either no tasks left or the pool shall stop
354                    * immediately, inform the waiting thread of a change
355                    * of the thread pool state.
356                    */
357                   g_cond_broadcast (&pool->cond);
358                 }
359             }
360
361           g_async_queue_unlock (pool->queue);
362
363           if (free_pool)
364             g_thread_pool_free_internal (pool);
365
366           if ((pool = g_thread_pool_wait_for_new_pool ()) == NULL)
367             break;
368
369           g_async_queue_lock (pool->queue);
370
371           DEBUG_MSG (("thread %p entering pool %p from global pool.",
372                       g_thread_self (), pool));
373
374           /* pool->num_threads++ is not done here, but in
375            * g_thread_pool_start_thread to make the new started
376            * thread known to the pool before itself can do it.
377            */
378         }
379     }
380
381   return NULL;
382 }
383
384 static gboolean
385 g_thread_pool_start_thread (GRealThreadPool  *pool,
386                             GError          **error)
387 {
388   gboolean success = FALSE;
389
390   if (pool->num_threads >= pool->max_threads && pool->max_threads != -1)
391     /* Enough threads are already running */
392     return TRUE;
393
394   g_async_queue_lock (unused_thread_queue);
395
396   if (g_async_queue_length_unlocked (unused_thread_queue) < 0)
397     {
398       g_async_queue_push_unlocked (unused_thread_queue, pool);
399       success = TRUE;
400     }
401
402   g_async_queue_unlock (unused_thread_queue);
403
404   if (!success)
405     {
406       GThread *thread;
407
408       /* No thread was found, we have to start a new one */
409       thread = g_thread_try_new ("pool", g_thread_pool_thread_proxy, pool, error);
410
411       if (thread == NULL)
412         return FALSE;
413
414       g_thread_unref (thread);
415     }
416
417   /* See comment in g_thread_pool_thread_proxy as to why this is done
418    * here and not there
419    */
420   pool->num_threads++;
421
422   return TRUE;
423 }
424
425 /**
426  * g_thread_pool_new:
427  * @func: a function to execute in the threads of the new thread pool
428  * @user_data: user data that is handed over to @func every time it
429  *     is called
430  * @max_threads: the maximal number of threads to execute concurrently
431  *     in  the new thread pool, -1 means no limit
432  * @exclusive: should this thread pool be exclusive?
433  * @error: return location for error, or %NULL
434  *
435  * This function creates a new thread pool.
436  *
437  * Whenever you call g_thread_pool_push(), either a new thread is
438  * created or an unused one is reused. At most @max_threads threads
439  * are running concurrently for this thread pool. @max_threads = -1
440  * allows unlimited threads to be created for this thread pool. The
441  * newly created or reused thread now executes the function @func
442  * with the two arguments. The first one is the parameter to
443  * g_thread_pool_push() and the second one is @user_data.
444  *
445  * The parameter @exclusive determines whether the thread pool owns
446  * all threads exclusive or shares them with other thread pools.
447  * If @exclusive is %TRUE, @max_threads threads are started
448  * immediately and they will run exclusively for this thread pool
449  * until it is destroyed by g_thread_pool_free(). If @exclusive is
450  * %FALSE, threads are created when needed and shared between all
451  * non-exclusive thread pools. This implies that @max_threads may
452  * not be -1 for exclusive thread pools.
453  *
454  * @error can be %NULL to ignore errors, or non-%NULL to report
455  * errors. An error can only occur when @exclusive is set to %TRUE
456  * and not all @max_threads threads could be created.
457  *
458  * Return value: the new #GThreadPool
459  */
460 GThreadPool *
461 g_thread_pool_new (GFunc      func,
462                    gpointer   user_data,
463                    gint       max_threads,
464                    gboolean   exclusive,
465                    GError   **error)
466 {
467   GRealThreadPool *retval;
468   G_LOCK_DEFINE_STATIC (init);
469
470   g_return_val_if_fail (func, NULL);
471   g_return_val_if_fail (!exclusive || max_threads != -1, NULL);
472   g_return_val_if_fail (max_threads >= -1, NULL);
473
474   retval = g_new (GRealThreadPool, 1);
475
476   retval->pool.func = func;
477   retval->pool.user_data = user_data;
478   retval->pool.exclusive = exclusive;
479   retval->queue = g_async_queue_new ();
480   g_cond_init (&retval->cond);
481   retval->max_threads = max_threads;
482   retval->num_threads = 0;
483   retval->running = TRUE;
484   retval->immediate = FALSE;
485   retval->waiting = FALSE;
486   retval->sort_func = NULL;
487   retval->sort_user_data = NULL;
488
489   G_LOCK (init);
490   if (!unused_thread_queue)
491       unused_thread_queue = g_async_queue_new ();
492   G_UNLOCK (init);
493
494   if (retval->pool.exclusive)
495     {
496       g_async_queue_lock (retval->queue);
497
498       while (retval->num_threads < retval->max_threads)
499         {
500           GError *local_error = NULL;
501
502           if (!g_thread_pool_start_thread (retval, &local_error))
503             {
504               g_propagate_error (error, local_error);
505               break;
506             }
507         }
508
509       g_async_queue_unlock (retval->queue);
510     }
511
512   return (GThreadPool*) retval;
513 }
514
515 /**
516  * g_thread_pool_push:
517  * @pool: a #GThreadPool
518  * @data: a new task for @pool
519  * @error: return location for error, or %NULL
520  *
521  * Inserts @data into the list of tasks to be executed by @pool.
522  *
523  * When the number of currently running threads is lower than the
524  * maximal allowed number of threads, a new thread is started (or
525  * reused) with the properties given to g_thread_pool_new().
526  * Otherwise, @data stays in the queue until a thread in this pool
527  * finishes its previous task and processes @data.
528  *
529  * @error can be %NULL to ignore errors, or non-%NULL to report
530  * errors. An error can only occur when a new thread couldn't be
531  * created. In that case @data is simply appended to the queue of
532  * work to do.
533  *
534  * Before version 2.32, this function did not return a success status.
535  *
536  * Return value: %TRUE on success, %FALSE if an error occurred
537  */
538 gboolean
539 g_thread_pool_push (GThreadPool  *pool,
540                     gpointer      data,
541                     GError      **error)
542 {
543   GRealThreadPool *real;
544   gboolean result;
545
546   real = (GRealThreadPool*) pool;
547
548   g_return_val_if_fail (real, FALSE);
549   g_return_val_if_fail (real->running, FALSE);
550
551   result = TRUE;
552
553   g_async_queue_lock (real->queue);
554
555   if (g_async_queue_length_unlocked (real->queue) >= 0)
556     {
557       /* No thread is waiting in the queue */
558       GError *local_error = NULL;
559
560       if (!g_thread_pool_start_thread (real, &local_error))
561         {
562           g_propagate_error (error, local_error);
563           result = FALSE;
564         }
565     }
566
567   g_thread_pool_queue_push_unlocked (real, data);
568   g_async_queue_unlock (real->queue);
569
570   return result;
571 }
572
573 /**
574  * g_thread_pool_set_max_threads:
575  * @pool: a #GThreadPool
576  * @max_threads: a new maximal number of threads for @pool,
577  *     or -1 for unlimited
578  * @error: return location for error, or %NULL
579  *
580  * Sets the maximal allowed number of threads for @pool.
581  * A value of -1 means that the maximal number of threads
582  * is unlimited. If @pool is an exclusive thread pool, setting
583  * the maximal number of threads to -1 is not allowed.
584  *
585  * Setting @max_threads to 0 means stopping all work for @pool.
586  * It is effectively frozen until @max_threads is set to a non-zero
587  * value again.
588  *
589  * A thread is never terminated while calling @func, as supplied by
590  * g_thread_pool_new(). Instead the maximal number of threads only
591  * has effect for the allocation of new threads in g_thread_pool_push().
592  * A new thread is allocated, whenever the number of currently
593  * running threads in @pool is smaller than the maximal number.
594  *
595  * @error can be %NULL to ignore errors, or non-%NULL to report
596  * errors. An error can only occur when a new thread couldn't be
597  * created.
598  *
599  * Before version 2.32, this function did not return a success status.
600  *
601  * Return value: %TRUE on success, %FALSE if an error occurred
602  */
603 gboolean
604 g_thread_pool_set_max_threads (GThreadPool  *pool,
605                                gint          max_threads,
606                                GError      **error)
607 {
608   GRealThreadPool *real;
609   gint to_start;
610   gboolean result;
611
612   real = (GRealThreadPool*) pool;
613
614   g_return_val_if_fail (real, FALSE);
615   g_return_val_if_fail (real->running, FALSE);
616   g_return_val_if_fail (!real->pool.exclusive || max_threads != -1, FALSE);
617   g_return_val_if_fail (max_threads >= -1, FALSE);
618
619   result = TRUE;
620
621   g_async_queue_lock (real->queue);
622
623   real->max_threads = max_threads;
624
625   if (pool->exclusive)
626     to_start = real->max_threads - real->num_threads;
627   else
628     to_start = g_async_queue_length_unlocked (real->queue);
629
630   for ( ; to_start > 0; to_start--)
631     {
632       GError *local_error = NULL;
633
634       if (!g_thread_pool_start_thread (real, &local_error))
635         {
636           g_propagate_error (error, local_error);
637           result = FALSE;
638           break;
639         }
640     }
641
642   g_async_queue_unlock (real->queue);
643
644   return result;
645 }
646
647 /**
648  * g_thread_pool_get_max_threads:
649  * @pool: a #GThreadPool
650  *
651  * Returns the maximal number of threads for @pool.
652  *
653  * Return value: the maximal number of threads
654  */
655 gint
656 g_thread_pool_get_max_threads (GThreadPool *pool)
657 {
658   GRealThreadPool *real;
659   gint retval;
660
661   real = (GRealThreadPool*) pool;
662
663   g_return_val_if_fail (real, 0);
664   g_return_val_if_fail (real->running, 0);
665
666   g_async_queue_lock (real->queue);
667   retval = real->max_threads;
668   g_async_queue_unlock (real->queue);
669
670   return retval;
671 }
672
673 /**
674  * g_thread_pool_get_num_threads:
675  * @pool: a #GThreadPool
676  *
677  * Returns the number of threads currently running in @pool.
678  *
679  * Return value: the number of threads currently running
680  */
681 guint
682 g_thread_pool_get_num_threads (GThreadPool *pool)
683 {
684   GRealThreadPool *real;
685   guint retval;
686
687   real = (GRealThreadPool*) pool;
688
689   g_return_val_if_fail (real, 0);
690   g_return_val_if_fail (real->running, 0);
691
692   g_async_queue_lock (real->queue);
693   retval = real->num_threads;
694   g_async_queue_unlock (real->queue);
695
696   return retval;
697 }
698
699 /**
700  * g_thread_pool_unprocessed:
701  * @pool: a #GThreadPool
702  *
703  * Returns the number of tasks still unprocessed in @pool.
704  *
705  * Return value: the number of unprocessed tasks
706  */
707 guint
708 g_thread_pool_unprocessed (GThreadPool *pool)
709 {
710   GRealThreadPool *real;
711   gint unprocessed;
712
713   real = (GRealThreadPool*) pool;
714
715   g_return_val_if_fail (real, 0);
716   g_return_val_if_fail (real->running, 0);
717
718   unprocessed = g_async_queue_length (real->queue);
719
720   return MAX (unprocessed, 0);
721 }
722
723 /**
724  * g_thread_pool_free:
725  * @pool: a #GThreadPool
726  * @immediate: should @pool shut down immediately?
727  * @wait_: should the function wait for all tasks to be finished?
728  *
729  * Frees all resources allocated for @pool.
730  *
731  * If @immediate is %TRUE, no new task is processed for @pool.
732  * Otherwise @pool is not freed before the last task is processed.
733  * Note however, that no thread of this pool is interrupted while
734  * processing a task. Instead at least all still running threads
735  * can finish their tasks before the @pool is freed.
736  *
737  * If @wait_ is %TRUE, the functions does not return before all
738  * tasks to be processed (dependent on @immediate, whether all
739  * or only the currently running) are ready.
740  * Otherwise the function returns immediately.
741  *
742  * After calling this function @pool must not be used anymore.
743  */
744 void
745 g_thread_pool_free (GThreadPool *pool,
746                     gboolean     immediate,
747                     gboolean     wait_)
748 {
749   GRealThreadPool *real;
750
751   real = (GRealThreadPool*) pool;
752
753   g_return_if_fail (real);
754   g_return_if_fail (real->running);
755
756   /* If there's no thread allowed here, there is not much sense in
757    * not stopping this pool immediately, when it's not empty
758    */
759   g_return_if_fail (immediate ||
760                     real->max_threads != 0 ||
761                     g_async_queue_length (real->queue) == 0);
762
763   g_async_queue_lock (real->queue);
764
765   real->running = FALSE;
766   real->immediate = immediate;
767   real->waiting = wait_;
768
769   if (wait_)
770     {
771       while (g_async_queue_length_unlocked (real->queue) != -real->num_threads &&
772              !(immediate && real->num_threads == 0))
773         g_cond_wait (&real->cond, _g_async_queue_get_mutex (real->queue));
774     }
775
776   if (immediate || g_async_queue_length_unlocked (real->queue) == -real->num_threads)
777     {
778       /* No thread is currently doing something (and nothing is left
779        * to process in the queue)
780        */
781       if (real->num_threads == 0)
782         {
783           /* No threads left, we clean up */
784           g_async_queue_unlock (real->queue);
785           g_thread_pool_free_internal (real);
786           return;
787         }
788
789       g_thread_pool_wakeup_and_stop_all (real);
790     }
791
792   /* The last thread should cleanup the pool */
793   real->waiting = FALSE;
794   g_async_queue_unlock (real->queue);
795 }
796
797 static void
798 g_thread_pool_free_internal (GRealThreadPool* pool)
799 {
800   g_return_if_fail (pool);
801   g_return_if_fail (pool->running == FALSE);
802   g_return_if_fail (pool->num_threads == 0);
803
804   g_async_queue_unref (pool->queue);
805   g_cond_clear (&pool->cond);
806
807   g_free (pool);
808 }
809
810 static void
811 g_thread_pool_wakeup_and_stop_all (GRealThreadPool *pool)
812 {
813   guint i;
814
815   g_return_if_fail (pool);
816   g_return_if_fail (pool->running == FALSE);
817   g_return_if_fail (pool->num_threads != 0);
818
819   pool->immediate = TRUE;
820
821   for (i = 0; i < pool->num_threads; i++)
822     g_thread_pool_queue_push_unlocked (pool, GUINT_TO_POINTER (1));
823 }
824
825 /**
826  * g_thread_pool_set_max_unused_threads:
827  * @max_threads: maximal number of unused threads
828  *
829  * Sets the maximal number of unused threads to @max_threads.
830  * If @max_threads is -1, no limit is imposed on the number
831  * of unused threads.
832  */
833 void
834 g_thread_pool_set_max_unused_threads (gint max_threads)
835 {
836   g_return_if_fail (max_threads >= -1);
837
838   g_atomic_int_set (&max_unused_threads, max_threads);
839
840   if (max_threads != -1)
841     {
842       max_threads -= g_atomic_int_get (&unused_threads);
843       if (max_threads < 0)
844         {
845           g_atomic_int_set (&kill_unused_threads, -max_threads);
846           g_atomic_int_inc (&wakeup_thread_serial);
847
848           g_async_queue_lock (unused_thread_queue);
849
850           do
851             {
852               g_async_queue_push_unlocked (unused_thread_queue,
853                                            wakeup_thread_marker);
854             }
855           while (++max_threads);
856
857           g_async_queue_unlock (unused_thread_queue);
858         }
859     }
860 }
861
862 /**
863  * g_thread_pool_get_max_unused_threads:
864  *
865  * Returns the maximal allowed number of unused threads.
866  *
867  * Return value: the maximal number of unused threads
868  */
869 gint
870 g_thread_pool_get_max_unused_threads (void)
871 {
872   return g_atomic_int_get (&max_unused_threads);
873 }
874
875 /**
876  * g_thread_pool_get_num_unused_threads:
877  *
878  * Returns the number of currently unused threads.
879  *
880  * Return value: the number of currently unused threads
881  */
882 guint
883 g_thread_pool_get_num_unused_threads (void)
884 {
885   return g_atomic_int_get (&unused_threads);
886 }
887
888 /**
889  * g_thread_pool_stop_unused_threads:
890  *
891  * Stops all currently unused threads. This does not change the
892  * maximal number of unused threads. This function can be used to
893  * regularly stop all unused threads e.g. from g_timeout_add().
894  */
895 void
896 g_thread_pool_stop_unused_threads (void)
897 {
898   guint oldval;
899
900   oldval = g_thread_pool_get_max_unused_threads ();
901
902   g_thread_pool_set_max_unused_threads (0);
903   g_thread_pool_set_max_unused_threads (oldval);
904 }
905
906 /**
907  * g_thread_pool_set_sort_function:
908  * @pool: a #GThreadPool
909  * @func: the #GCompareDataFunc used to sort the list of tasks.
910  *     This function is passed two tasks. It should return
911  *     0 if the order in which they are handled does not matter,
912  *     a negative value if the first task should be processed before
913  *     the second or a positive value if the second task should be
914  *     processed first.
915  * @user_data: user data passed to @func
916  *
917  * Sets the function used to sort the list of tasks. This allows the
918  * tasks to be processed by a priority determined by @func, and not
919  * just in the order in which they were added to the pool.
920  *
921  * Note, if the maximum number of threads is more than 1, the order
922  * that threads are executed cannot be guaranteed 100%. Threads are
923  * scheduled by the operating system and are executed at random. It
924  * cannot be assumed that threads are executed in the order they are
925  * created.
926  *
927  * Since: 2.10
928  */
929 void
930 g_thread_pool_set_sort_function (GThreadPool      *pool,
931                                  GCompareDataFunc  func,
932                                  gpointer          user_data)
933 {
934   GRealThreadPool *real;
935
936   real = (GRealThreadPool*) pool;
937
938   g_return_if_fail (real);
939   g_return_if_fail (real->running);
940
941   g_async_queue_lock (real->queue);
942
943   real->sort_func = func;
944   real->sort_user_data = user_data;
945
946   if (func)
947     g_async_queue_sort_unlocked (real->queue,
948                                  real->sort_func,
949                                  real->sort_user_data);
950
951   g_async_queue_unlock (real->queue);
952 }
953
954 /**
955  * g_thread_pool_set_max_idle_time:
956  * @interval: the maximum @interval (in milliseconds)
957  *     a thread can be idle
958  *
959  * This function will set the maximum @interval that a thread
960  * waiting in the pool for new tasks can be idle for before
961  * being stopped. This function is similar to calling
962  * g_thread_pool_stop_unused_threads() on a regular timeout,
963  * except this is done on a per thread basis.
964  *
965  * By setting @interval to 0, idle threads will not be stopped.
966  *
967  * This function makes use of g_async_queue_timed_pop () using
968  * @interval.
969  *
970  * Since: 2.10
971  */
972 void
973 g_thread_pool_set_max_idle_time (guint interval)
974 {
975   guint i;
976
977   g_atomic_int_set (&max_idle_time, interval);
978
979   i = g_atomic_int_get (&unused_threads);
980   if (i > 0)
981     {
982       g_atomic_int_inc (&wakeup_thread_serial);
983       g_async_queue_lock (unused_thread_queue);
984
985       do
986         {
987           g_async_queue_push_unlocked (unused_thread_queue,
988                                        wakeup_thread_marker);
989         }
990       while (--i);
991
992       g_async_queue_unlock (unused_thread_queue);
993     }
994 }
995
996 /**
997  * g_thread_pool_get_max_idle_time:
998  *
999  * This function will return the maximum @interval that a
1000  * thread will wait in the thread pool for new tasks before
1001  * being stopped.
1002  *
1003  * If this function returns 0, threads waiting in the thread
1004  * pool for new work are not stopped.
1005  *
1006  * Return value: the maximum @interval (milliseconds) to wait
1007  *     for new tasks in the thread pool before stopping the
1008  *     thread
1009  *
1010  * Since: 2.10
1011  */
1012 guint
1013 g_thread_pool_get_max_idle_time (void)
1014 {
1015   return g_atomic_int_get (&max_idle_time);
1016 }