Clarification for g_mutex_trylock.
[platform/upstream/glib.git] / 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  * GAsyncQueue: 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 "glib.h"
28
29 typedef struct _GRealThreadPool GRealThreadPool;
30
31 struct _GRealThreadPool
32 {
33   GThreadPool pool;
34   GAsyncQueue* queue;
35   gint max_threads;
36   gint num_threads;
37   gboolean running;
38   gboolean immediate;
39   gboolean waiting;
40 };
41
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;
46
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);
52
53 static GMutex *inform_mutex = NULL;
54 static GCond *inform_cond = NULL;
55
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, 
59                                             GError **error);
60 static void     g_thread_pool_wakeup_and_stop_all (GRealThreadPool* pool);
61
62 #define g_thread_should_run(pool, len) \
63   ((pool)->running || (!(pool)->immediate && (len) > 0))
64
65 static gpointer 
66 g_thread_pool_thread_proxy (gpointer data)
67 {
68   GRealThreadPool *pool = data;
69   gboolean watcher = FALSE;
70
71   g_async_queue_lock (pool->queue);
72   while (TRUE)
73     {
74       gpointer task; 
75       gboolean goto_global_pool = 
76         !pool->pool.exclusive && pool->pool.stack_size == 0;
77       gint len = g_async_queue_length_unlocked (pool->queue);
78       
79       if (g_thread_should_run (pool, len))
80         {
81           if (watcher)
82             {
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
87                * pool afterwards */
88               GTimeVal end_time;
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)
92                 {
93                   end_time.tv_usec -= G_USEC_PER_SEC;
94                   end_time.tv_sec += 1;
95                 }
96          
97               task = g_async_queue_timed_pop_unlocked (pool->queue, &end_time);
98             }
99           else
100             {
101               task = g_async_queue_pop_unlocked (pool->queue);
102             }
103
104           if (task)
105             {
106               watcher = FALSE;
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 */
112                 {
113                   g_async_queue_push_unlocked (pool->queue, task);
114                   goto_global_pool = TRUE;
115                 }
116               else if (pool->running || !pool->immediate)
117                 {
118                   g_async_queue_unlock (pool->queue);
119                   pool->pool.thread_func (task, pool->pool.user_data);
120                   g_async_queue_lock (pool->queue);
121                 }
122             }
123           len = g_async_queue_length_unlocked (pool->queue);
124         }
125
126       if (!g_thread_should_run (pool, len))
127         {
128           g_cond_broadcast (inform_cond);
129           goto_global_pool = TRUE;
130         }
131       else if (len > 0)
132         {
133           /* At this pool there are no threads waiting, but tasks are. */
134           goto_global_pool = FALSE; 
135         }
136       else if (len == 0 && !watcher && !pool->pool.exclusive)
137         {
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
141            * switches. */
142           goto_global_pool = FALSE;
143           watcher = TRUE;
144         }
145
146       
147       if (goto_global_pool)
148         {
149           GAsyncQueue *unused_queue = 
150             unused_thread_queue[pool->pool.priority][pool->pool.bound ? 1 : 0];
151           pool->num_threads--; 
152
153           if (!pool->running && !pool->waiting)
154             {
155               if (pool->num_threads == 0)
156                 {
157                   g_async_queue_unlock (pool->queue);
158                   g_thread_pool_free_internal (pool);
159                 }               
160               else if (len == - pool->num_threads)
161                 {
162                   g_thread_pool_wakeup_and_stop_all (pool);
163                   g_async_queue_unlock (pool->queue);
164                 }
165             }
166           else
167             g_async_queue_unlock (pool->queue);
168           
169           g_async_queue_lock (unused_queue);
170
171           G_LOCK (unused_threads);
172           if ((unused_threads >= max_unused_threads && 
173                max_unused_threads != -1) || pool->pool.stack_size != 0)
174             {
175               G_UNLOCK (unused_threads);
176               g_async_queue_unlock (unused_queue);
177               /* Stop this thread */
178               return NULL;      
179             }
180           unused_threads++;
181           G_UNLOCK (unused_threads);
182
183           pool = g_async_queue_pop_unlocked (unused_queue);
184
185           G_LOCK (unused_threads);
186           unused_threads--;
187           G_UNLOCK (unused_threads);
188
189           g_async_queue_unlock (unused_queue);
190           
191           if (pool == stop_this_thread_marker)
192             /* Stop this thread */
193             return NULL;
194           
195           g_async_queue_lock (pool->queue);
196
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. */
200         }
201     }
202   return NULL;
203 }
204
205 static void
206 g_thread_pool_start_thread (GRealThreadPool  *pool, 
207                             GError          **error)
208 {
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];
213   
214   if (pool->num_threads >= pool->max_threads && pool->max_threads != -1)
215     /* Enough threads are already running */
216     return;
217
218   g_async_queue_lock (queue);
219
220   if (g_async_queue_length_unlocked (queue) < 0)
221     {
222       /* First we try a thread with the right priority */
223       g_async_queue_push_unlocked (queue, pool);
224       success = TRUE;
225     }
226
227   g_async_queue_unlock (queue);
228
229   /* We will not search for threads with other priorities, because changing
230    * priority is quite unportable */
231   
232   if (!success)
233     {
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);
239       
240       if (local_error)
241         {
242           g_propagate_error (error, local_error);
243           return;
244         }
245     }
246
247   /* See comment in g_thread_pool_thread_proxy as to why this is done
248    * here and not there */
249   pool->num_threads++;
250 }
251
252 /**
253  * g_thread_pool_new: 
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 
263  *   is called
264  * @error: return location for error
265  *
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
269  * true. 
270  *
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.
278  *
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.
287  *
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.
293  *
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.
297  *
298  * Return value: the new #GThreadPool
299  **/
300 GThreadPool* 
301 g_thread_pool_new (GFunc            thread_func,
302                    gint             max_threads,
303                    gulong           stack_size,
304                    gboolean         bound,
305                    GThreadPriority  priority,
306                    gboolean         exclusive,
307                    gpointer         user_data,
308                    GError         **error)
309 {
310   GRealThreadPool *retval;
311   G_LOCK_DEFINE_STATIC (init);
312
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);
317
318   retval = g_new (GRealThreadPool, 1);
319
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;
330
331   G_LOCK (init);
332   
333   if (!inform_mutex)
334     {
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++)
339         {
340           unused_thread_queue[priority][0] = g_async_queue_new ();
341           unused_thread_queue[priority][1] = g_async_queue_new ();
342         }
343     }
344
345   G_UNLOCK (init);
346
347   if (retval->pool.exclusive)
348     {
349       g_async_queue_lock (retval->queue);
350   
351       while (retval->num_threads < retval->max_threads)
352         {
353           GError *local_error = NULL;
354           g_thread_pool_start_thread (retval, &local_error);
355           if (local_error)
356             {
357               g_propagate_error (error, local_error);
358               break;
359             }
360         }
361
362       g_async_queue_unlock (retval->queue);
363     }
364
365   return (GThreadPool*) retval;
366 }
367
368 /**
369  * g_thread_pool_push:
370  * @pool: a #GThreadPool
371  * @data: a new task for @pool
372  * @error: return location for error
373  * 
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. 
380  *
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
384  * to do.  
385  **/
386 void 
387 g_thread_pool_push (GThreadPool     *pool,
388                     gpointer         data,
389                     GError         **error)
390 {
391   GRealThreadPool *real = (GRealThreadPool*) pool;
392
393   g_return_if_fail (real);
394
395   g_async_queue_lock (real->queue);
396   
397   if (!real->running)
398     {
399       g_async_queue_unlock (real->queue);
400       g_return_if_fail (real->running);
401     }
402
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);
406
407   g_async_queue_push_unlocked (real->queue, data);
408   g_async_queue_unlock (real->queue);
409 }
410
411 /**
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
416  * 
417  * Sets the maximal allowed number of threads for @pool. A value of -1
418  * means, that the maximal number of threads is unlimited.
419  *
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
422  * again.
423  * 
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
429  * maximal number.
430  *
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
433  * created. 
434  **/
435 void
436 g_thread_pool_set_max_threads (GThreadPool     *pool,
437                                gint             max_threads,
438                                GError         **error)
439 {
440   GRealThreadPool *real = (GRealThreadPool*) pool;
441   gint to_start;
442
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);
447
448   g_async_queue_lock (real->queue);
449
450   real->max_threads = max_threads;
451   
452   if (pool->exclusive)
453     to_start = real->max_threads - real->num_threads;
454   else
455     to_start = g_async_queue_length_unlocked (real->queue);
456   
457   for ( ; to_start > 0; to_start--)
458     {
459       GError *local_error = NULL;
460       g_thread_pool_start_thread (real, &local_error);
461       if (local_error)
462         {
463           g_propagate_error (error, local_error);
464           break;
465         }
466     }
467    
468   g_async_queue_unlock (real->queue);
469 }
470
471 /**
472  * g_thread_pool_get_max_threads:
473  * @pool: a #GThreadPool
474  *
475  * Returns the maximal number of threads for @pool.
476  *
477  * Return value: the maximal number of threads
478  **/
479 gint
480 g_thread_pool_get_max_threads (GThreadPool     *pool)
481 {
482   GRealThreadPool *real = (GRealThreadPool*) pool;
483   gint retval;
484
485   g_return_val_if_fail (real, 0);
486   g_return_val_if_fail (real->running, 0);
487
488   g_async_queue_lock (real->queue);
489
490   retval = real->max_threads;
491     
492   g_async_queue_unlock (real->queue);
493
494   return retval;
495 }
496
497 /**
498  * g_thread_pool_get_num_threads:
499  * @pool: a #GThreadPool
500  *
501  * Returns the number of threads currently running in @pool.
502  *
503  * Return value: the number of threads currently running
504  **/
505 guint
506 g_thread_pool_get_num_threads (GThreadPool     *pool)
507 {
508   GRealThreadPool *real = (GRealThreadPool*) pool;
509   guint retval;
510
511   g_return_val_if_fail (real, 0);
512   g_return_val_if_fail (real->running, 0);
513
514   g_async_queue_lock (real->queue);
515
516   retval = real->num_threads;
517     
518   g_async_queue_unlock (real->queue);
519
520   return retval;
521 }
522
523 /**
524  * g_thread_pool_unprocessed:
525  * @pool: a #GThreadPool
526  *
527  * Returns the number of tasks still unprocessed in @pool.
528  *
529  * Return value: the number of unprocessed tasks
530  **/
531 guint
532 g_thread_pool_unprocessed (GThreadPool     *pool)
533 {
534   GRealThreadPool *real = (GRealThreadPool*) pool;
535   gint unprocessed;
536
537   g_return_val_if_fail (real, 0);
538   g_return_val_if_fail (real->running, 0);
539
540   unprocessed = g_async_queue_length (real->queue);
541
542   return MAX (unprocessed, 0);
543 }
544
545 /**
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?
550  *
551  * Frees all resources allocated for @pool.
552  *
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.
558  *
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.
562  *
563  * After calling this function @pool must not be used anymore. 
564  **/
565 void
566 g_thread_pool_free (GThreadPool     *pool,
567                     gboolean         immediate,
568                     gboolean         wait)
569 {
570   GRealThreadPool *real = (GRealThreadPool*) pool;
571
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);
578
579   g_async_queue_lock (real->queue);
580
581   real->running = FALSE;
582   real->immediate = immediate;
583   real->waiting = wait;
584
585   if (wait)
586     {
587       g_mutex_lock (inform_mutex);
588       while (g_async_queue_length_unlocked (real->queue) != -real->num_threads)
589         {
590           g_async_queue_unlock (real->queue); 
591           g_cond_wait (inform_cond, inform_mutex); 
592           g_async_queue_lock (real->queue); 
593         }
594       g_mutex_unlock (inform_mutex); 
595     }
596
597   if (g_async_queue_length_unlocked (real->queue) == -real->num_threads)
598     {
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 */
602         {
603           g_async_queue_unlock (real->queue);
604           g_thread_pool_free_internal (real);
605           return;
606         }
607
608       g_thread_pool_wakeup_and_stop_all (real);
609     }
610   
611   real->waiting = FALSE; /* The last thread should cleanup the pool */
612   g_async_queue_unlock (real->queue);
613 }
614
615 static void
616 g_thread_pool_free_internal (GRealThreadPool* pool)
617 {
618   g_return_if_fail (pool);
619   g_return_if_fail (!pool->running);
620   g_return_if_fail (pool->num_threads == 0);
621
622   g_async_queue_unref (pool->queue);
623
624   g_free (pool);
625 }
626
627 static void
628 g_thread_pool_wakeup_and_stop_all (GRealThreadPool* pool)
629 {
630   guint i;
631   
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) == 
636                     -pool->num_threads);
637
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));
641 }
642
643 /**
644  * g_thread_pool_set_max_unused_threads:
645  * @max_threads: maximal number of unused threads
646  *
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
649  * threads.
650  **/
651 void
652 g_thread_pool_set_max_unused_threads (gint max_threads)
653 {
654   g_return_if_fail (max_threads >= -1);  
655
656   G_LOCK (unused_threads);
657   
658   max_unused_threads = max_threads;
659
660   if (max_unused_threads < unused_threads && max_unused_threads != -1)
661     {
662       guint close_down_num = unused_threads - max_unused_threads;
663
664       while (close_down_num > 0)
665         {
666           GThreadPriority priority;
667           guint bound;
668
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; 
672                priority++)
673             {
674               for (bound = 0; bound < 2; bound++)
675                 {
676                   GAsyncQueue *queue = unused_thread_queue[priority][bound];
677                   g_async_queue_lock (queue);
678                   
679                   if (g_async_queue_length_unlocked (queue) < 0)
680                     {
681                       g_async_queue_push_unlocked (queue, 
682                                                    stop_this_thread_marker);
683                       close_down_num--;
684                     }
685                   
686                   g_async_queue_unlock (queue);
687                 }
688             }
689
690           /* Just to make sure, there are no counting problems */
691           g_assert (old_close_down_num != close_down_num);
692         }
693     }
694     
695   G_UNLOCK (unused_threads);
696 }
697
698 /**
699  * g_thread_pool_get_max_unused_threads:
700  * 
701  * Returns the maximal allowed number of unused threads.
702  *
703  * Return value: the maximal number of unused threads
704  **/
705 gint
706 g_thread_pool_get_max_unused_threads (void)
707 {
708   gint retval;
709   
710   G_LOCK (unused_threads);
711   retval = max_unused_threads;
712   G_UNLOCK (unused_threads);
713
714   return retval;
715 }
716
717 /**
718  * g_thread_pool_get_num_unused_threads:
719  * 
720  * Returns the number of currently unused threads.
721  *
722  * Return value: the number of currently unused threads
723  **/
724 guint g_thread_pool_get_num_unused_threads (void)
725 {
726   guint retval;
727   
728   G_LOCK (unused_threads);
729   retval = unused_threads;
730   G_UNLOCK (unused_threads);
731
732   return retval;
733 }
734
735 /**
736  * g_thread_pool_stop_unused_threads:
737  * 
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().
741  **/
742 void g_thread_pool_stop_unused_threads (void)
743
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);
747 }