#include <gerror.h>
[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 Library 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  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library 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 = &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];
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 void g_thread_pool_thread_proxy (gpointer data);
58 static void g_thread_pool_start_thread (GRealThreadPool* pool);
59 static void g_thread_pool_wakeup_and_stop_all (GRealThreadPool* pool);
60
61 #define g_thread_should_run(pool, len) \
62   ((pool)->running || (!(pool)->immediate && (len) > 0))
63
64 static void 
65 g_thread_pool_thread_proxy (gpointer data)
66 {
67   GRealThreadPool *pool = data;
68   GThread* self = g_thread_self ();
69
70   g_async_queue_lock (pool->queue);
71   while (TRUE)
72     {
73       gpointer task; 
74       gboolean goto_global_pool = !pool->pool.exclusive;
75       gint len = g_async_queue_length_unlocked (pool->queue);
76       
77       if (g_thread_should_run (pool, len))
78         {
79           task = g_async_queue_pop_unlocked (pool->queue);
80
81           if (pool->num_threads > pool->max_threads && pool->max_threads != -1)
82             /* We are in fact a superfluous threads, so we go to the
83              * global pool and just hand the data further to the next one
84              * waiting in the queue */
85             {
86               g_async_queue_push_unlocked (pool->queue, task);
87               goto_global_pool = TRUE;
88             }
89           else if (pool->running || !pool->immediate)
90             {
91               g_async_queue_unlock (pool->queue);
92               pool->pool.thread_func (task, pool->pool.user_data);
93               g_async_queue_lock (pool->queue);
94             }
95
96           len = g_async_queue_length_unlocked (pool->queue);
97         }
98
99       if (!g_thread_should_run (pool, len))
100         g_cond_broadcast (inform_cond);
101       
102       if (!pool->running && (pool->immediate || len <= 0))
103         goto_global_pool = TRUE;
104       else if (len >= 0)
105         /* At this pool there is no thread waiting */
106         goto_global_pool = FALSE; 
107       
108       if (goto_global_pool)
109         {
110           GThreadPriority priority = pool->pool.priority;
111           pool->num_threads--; 
112
113           if (!pool->running && !pool->waiting)
114             {
115               if (pool->num_threads == 0)
116                 {
117                   g_async_queue_unlock (pool->queue);
118                   g_thread_pool_free_internal (pool);
119                 }               
120               else if (len == - pool->num_threads)
121                 g_thread_pool_wakeup_and_stop_all (pool);
122             }
123           else
124             g_async_queue_unlock (pool->queue);
125           
126           g_async_queue_lock (unused_thread_queue[priority]);
127
128           G_LOCK (unused_threads);
129           if (unused_threads >= max_unused_threads)
130             {
131               G_UNLOCK (unused_threads);
132               g_async_queue_unlock (unused_thread_queue[priority]);
133               /* Stop this thread */
134               return;      
135             }
136           unused_threads++;
137           G_UNLOCK (unused_threads);
138
139           pool = 
140             g_async_queue_pop_unlocked (unused_thread_queue[priority]);
141
142           G_LOCK (unused_threads);
143           unused_threads--;
144           G_UNLOCK (unused_threads);
145
146           g_async_queue_unlock (unused_thread_queue[priority]);
147           
148           if (pool == stop_this_thread_marker)
149             /* Stop this thread */
150             return;
151           
152           g_async_queue_lock (pool->queue);
153
154           if (pool->pool.priority != self->priority)
155             g_thread_set_priority (self, pool->pool.priority);
156
157           /* pool->num_threads++ is not done here, but in
158            * g_thread_pool_start_thread to make the new started thread
159            * known to the pool, before itself can do it. */
160         }
161     }
162 }
163
164 static void
165 g_thread_pool_start_thread (GRealThreadPool* pool)
166 {
167   gboolean success = FALSE;
168   GThreadPriority priority = pool->pool.priority;
169   GAsyncQueue *queue = unused_thread_queue[priority];
170   
171   if (pool->num_threads >= pool->max_threads && pool->max_threads != -1)
172     /* Enough threads are already running */
173     return;
174
175   g_async_queue_lock (queue);
176
177   if (g_async_queue_length_unlocked (queue) < 0)
178     {
179       /* First we try a thread with the right priority */
180       g_async_queue_push_unlocked (queue, pool);
181       success = TRUE;
182     }
183
184   g_async_queue_unlock (queue);
185
186   if (!success)
187     {
188       /* Now we search for threads with other priorities too, but
189        * only, when there is more than one unused thread with that
190        * priority. */
191       GThreadPriority priority;
192       for (priority = G_THREAD_PRIORITY_LOW; 
193            priority < G_THREAD_PRIORITY_URGENT + 1; priority++)
194         {
195           queue = unused_thread_queue[priority];
196           g_async_queue_lock (queue);
197           
198           if (g_async_queue_length_unlocked (queue) < -1)
199             {
200               g_async_queue_push_unlocked (queue, pool);
201               success = TRUE;
202             }
203           
204           g_async_queue_unlock (queue);
205         }      
206     }
207
208   if (!success)
209     /* No thread was found, we have to start one new */
210     g_thread_create (g_thread_pool_thread_proxy, pool, pool->pool.stack_size, 
211                      FALSE, pool->pool.bound, priority);
212
213   /* See comment in g_thread_pool_thread_proxy as to why this is done
214    * here and not there */
215   pool->num_threads++;
216 }
217
218 GThreadPool* 
219 g_thread_pool_new (GFunc            thread_func,
220                    gint             max_threads,
221                    gulong           stack_size,
222                    gboolean         bound,
223                    GThreadPriority  priority,
224                    gboolean         exclusive,
225                    gpointer         user_data)
226 {
227   GRealThreadPool *retval;
228
229   g_return_val_if_fail (thread_func, NULL);
230   g_return_val_if_fail (!exclusive || max_threads != -1, NULL);
231   g_return_val_if_fail (max_threads >= -1, NULL);
232   g_return_val_if_fail (g_thread_supported (), NULL);
233
234   retval = g_new (GRealThreadPool, 1);
235
236   retval->pool.thread_func = thread_func;
237   retval->pool.stack_size = stack_size;
238   retval->pool.bound = bound;
239   retval->pool.priority = priority;
240   retval->pool.exclusive = exclusive;
241   retval->pool.user_data = user_data;
242
243   retval->queue = g_async_queue_new ();
244   retval->max_threads = max_threads;
245   retval->num_threads = 0;
246   retval->running = TRUE;
247
248   if (!inform_mutex)
249     {
250       inform_mutex = g_mutex_new ();
251       inform_cond = g_cond_new ();
252       for (priority = G_THREAD_PRIORITY_LOW; 
253            priority < G_THREAD_PRIORITY_URGENT + 1; priority++)
254         unused_thread_queue[priority] = g_async_queue_new ();
255     }
256
257   if (retval->pool.exclusive)
258     {
259       g_async_queue_lock (retval->queue);
260
261       while (retval->num_threads < retval->max_threads)
262         g_thread_pool_start_thread (retval);
263
264       g_async_queue_unlock (retval->queue);
265     }
266
267   return (GThreadPool*) retval;
268 }
269
270 void 
271 g_thread_pool_push (GThreadPool     *pool,
272                     gpointer         data)
273 {
274   GRealThreadPool *real = (GRealThreadPool*) pool;
275
276   g_return_if_fail (real);
277
278   g_async_queue_lock (real->queue);
279   
280   if (!real->running)
281     {
282       g_async_queue_unlock (real->queue);
283       g_return_if_fail (real->running);
284     }
285
286   if (!pool->exclusive && g_async_queue_length_unlocked (real->queue) >= 0)
287     {
288       /* No thread is waiting in the queue */
289       g_thread_pool_start_thread (real);
290     }
291   g_async_queue_push_unlocked (real->queue, data);
292   g_async_queue_unlock (real->queue);
293 }
294
295 void
296 g_thread_pool_set_max_threads (GThreadPool     *pool,
297                                gint             max_threads)
298 {
299   GRealThreadPool *real = (GRealThreadPool*) pool;
300   gint to_start;
301
302   g_return_if_fail (real);
303   g_return_if_fail (real->running);
304   g_return_if_fail (!real->pool.exclusive || max_threads != -1);
305   g_return_if_fail (max_threads >= -1);
306
307   g_async_queue_lock (real->queue);
308
309   real->max_threads = max_threads;
310   
311   if (pool->exclusive)
312     to_start = real->max_threads - real->num_threads;
313   else
314     to_start = g_async_queue_length_unlocked (real->queue);
315   
316   for ( ; to_start > 0; to_start--)
317     g_thread_pool_start_thread (real);
318     
319   g_async_queue_unlock (real->queue);
320 }
321
322 gint
323 g_thread_pool_get_max_threads (GThreadPool     *pool)
324 {
325   GRealThreadPool *real = (GRealThreadPool*) pool;
326   gint retval;
327
328   g_return_val_if_fail (real, 0);
329   g_return_val_if_fail (real->running, 0);
330
331   g_async_queue_lock (real->queue);
332
333   retval = real->max_threads;
334     
335   g_async_queue_unlock (real->queue);
336
337   return retval;
338 }
339
340 guint
341 g_thread_pool_get_num_threads (GThreadPool     *pool)
342 {
343   GRealThreadPool *real = (GRealThreadPool*) pool;
344   guint retval;
345
346   g_return_val_if_fail (real, 0);
347   g_return_val_if_fail (real->running, 0);
348
349   g_async_queue_lock (real->queue);
350
351   retval = real->num_threads;
352     
353   g_async_queue_unlock (real->queue);
354
355   return retval;
356 }
357
358 guint
359 g_thread_pool_unprocessed (GThreadPool     *pool)
360 {
361   GRealThreadPool *real = (GRealThreadPool*) pool;
362   gint unprocessed;
363
364   g_return_val_if_fail (real, 0);
365   g_return_val_if_fail (real->running, 0);
366
367   unprocessed = g_async_queue_length (real->queue);
368
369   return MAX (unprocessed, 0);
370 }
371
372 void
373 g_thread_pool_free (GThreadPool     *pool,
374                     gboolean         immediate,
375                     gboolean         wait)
376 {
377   GRealThreadPool *real = (GRealThreadPool*) pool;
378
379   g_return_if_fail (real);
380   g_return_if_fail (real->running);
381   /* It there's no thread allowed here, there is not much sense in
382    * not stopping this pool immediatly, when it's not empty */
383   g_return_if_fail (immediate || real->max_threads != 0 || 
384                     g_async_queue_length (real->queue) == 0);
385
386   g_async_queue_lock (real->queue);
387
388   real->running = FALSE;
389   real->immediate = immediate;
390   real->waiting = wait;
391
392   if (wait)
393     {
394       g_mutex_lock (inform_mutex);
395       while (g_async_queue_length_unlocked (real->queue) != -real->num_threads)
396         {
397           g_async_queue_unlock (real->queue); 
398           g_cond_wait (inform_cond, inform_mutex); 
399           g_async_queue_lock (real->queue); 
400         }
401       g_mutex_unlock (inform_mutex); 
402     }
403
404   if (g_async_queue_length_unlocked (real->queue) == -real->num_threads)
405     {
406       /* No thread is currently doing something (and nothing is left
407        * to process in the queue) */
408       if (real->num_threads == 0) /* No threads left, we clean up */
409         {
410           g_async_queue_unlock (real->queue);
411           g_thread_pool_free_internal (real);
412           return;
413         }
414
415       g_thread_pool_wakeup_and_stop_all (real);
416     }
417   
418   real->waiting = FALSE; /* The last thread should cleanup the pool */
419   g_async_queue_unlock (real->queue);
420 }
421
422 static void
423 g_thread_pool_free_internal (GRealThreadPool* pool)
424 {
425   g_return_if_fail (pool);
426   g_return_if_fail (!pool->running);
427   g_return_if_fail (pool->num_threads == 0);
428
429   g_async_queue_unref (pool->queue);
430
431   g_free (pool);
432 }
433
434 static void
435 g_thread_pool_wakeup_and_stop_all (GRealThreadPool* pool)
436 {
437   guint i;
438   
439   g_return_if_fail (pool);
440   g_return_if_fail (!pool->running);
441   g_return_if_fail (pool->num_threads != 0);
442   g_return_if_fail (g_async_queue_length_unlocked (pool->queue) == 
443                     -pool->num_threads);
444
445   pool->immediate = TRUE; 
446   for (i = 0; i < pool->num_threads; i++)
447     g_async_queue_push_unlocked (pool->queue, GUINT_TO_POINTER (1));
448 }
449
450 void
451 g_thread_pool_set_max_unused_threads (gint max_threads)
452 {
453   g_return_if_fail (max_threads >= -1);  
454
455   G_LOCK (unused_threads);
456   
457   max_unused_threads = max_threads;
458
459   if (max_unused_threads < unused_threads && max_unused_threads != -1)
460     {
461       guint close_down_num = unused_threads - max_unused_threads;
462       GThreadPriority priority;
463
464       while (close_down_num > 0)
465         {
466           guint old_close_down_num = close_down_num;
467           for (priority = G_THREAD_PRIORITY_LOW; 
468                priority < G_THREAD_PRIORITY_URGENT + 1 && close_down_num > 0; 
469                priority++)
470             {
471               GAsyncQueue *queue = unused_thread_queue[priority];
472               g_async_queue_lock (queue);
473               
474               if (g_async_queue_length_unlocked (queue) < 0)
475                 {
476                   g_async_queue_push_unlocked (queue, 
477                                                stop_this_thread_marker);
478                   close_down_num--;
479                 }
480               
481               g_async_queue_unlock (queue);
482             }
483
484           /* Just to make sure, there are no counting problems */
485           g_assert (old_close_down_num != close_down_num);
486         }
487     }
488     
489   G_UNLOCK (unused_threads);
490 }
491
492 gint
493 g_thread_pool_get_max_unused_threads (void)
494 {
495   gint retval;
496   
497   G_LOCK (unused_threads);
498   retval = max_unused_threads;
499   G_UNLOCK (unused_threads);
500
501   return retval;
502 }
503
504 guint g_thread_pool_get_num_unused_threads (void)
505 {
506   guint retval;
507   
508   G_LOCK (unused_threads);
509   retval = unused_threads;
510   G_UNLOCK (unused_threads);
511
512   return retval;
513 }
514
515 void g_thread_pool_stop_unused_threads (void)
516
517   guint oldval = g_thread_pool_get_max_unused_threads ();
518   g_thread_pool_set_max_unused_threads (0);
519   g_thread_pool_set_max_unused_threads (oldval);
520 }