Check for the sched.h header and include it on gthread/gthread-posix.c if
[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];
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, GError **error);
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           /* pool->num_threads++ is not done here, but in
155            * g_thread_pool_start_thread to make the new started thread
156            * known to the pool, before itself can do it. */
157         }
158     }
159 }
160
161 static void
162 g_thread_pool_start_thread (GRealThreadPool  *pool, 
163                             GError          **error)
164 {
165   gboolean success = FALSE;
166   GThreadPriority priority = pool->pool.priority;
167   GAsyncQueue *queue = unused_thread_queue[priority];
168   
169   if (pool->num_threads >= pool->max_threads && pool->max_threads != -1)
170     /* Enough threads are already running */
171     return;
172
173   g_async_queue_lock (queue);
174
175   if (g_async_queue_length_unlocked (queue) < 0)
176     {
177       /* First we try a thread with the right priority */
178       g_async_queue_push_unlocked (queue, pool);
179       success = TRUE;
180     }
181
182   g_async_queue_unlock (queue);
183
184   /* We will not search for threads with other priorities, because changing
185    * priority is quite unportable */
186   
187   if (!success)
188     {
189       GError *local_error = NULL;
190       /* No thread was found, we have to start one new */
191       g_thread_create (g_thread_pool_thread_proxy, pool, 
192                        pool->pool.stack_size, FALSE, 
193                        pool->pool.bound, priority, &local_error);
194       
195       if (local_error)
196         {
197           g_propagate_error (error, local_error);
198           return;
199         }
200     }
201
202   /* See comment in g_thread_pool_thread_proxy as to why this is done
203    * here and not there */
204   pool->num_threads++;
205 }
206
207 GThreadPool* 
208 g_thread_pool_new (GFunc            thread_func,
209                    gint             max_threads,
210                    gulong           stack_size,
211                    gboolean         bound,
212                    GThreadPriority  priority,
213                    gboolean         exclusive,
214                    gpointer         user_data,
215                    GError         **error)
216 {
217   GRealThreadPool *retval;
218
219   g_return_val_if_fail (thread_func, NULL);
220   g_return_val_if_fail (!exclusive || max_threads != -1, NULL);
221   g_return_val_if_fail (max_threads >= -1, NULL);
222   g_return_val_if_fail (g_thread_supported (), NULL);
223
224   retval = g_new (GRealThreadPool, 1);
225
226   retval->pool.thread_func = thread_func;
227   retval->pool.stack_size = stack_size;
228   retval->pool.bound = bound;
229   retval->pool.priority = priority;
230   retval->pool.exclusive = exclusive;
231   retval->pool.user_data = user_data;
232   retval->queue = g_async_queue_new ();
233   retval->max_threads = max_threads;
234   retval->num_threads = 0;
235   retval->running = TRUE;
236
237   if (!inform_mutex)
238     {
239       inform_mutex = g_mutex_new ();
240       inform_cond = g_cond_new ();
241       for (priority = G_THREAD_PRIORITY_LOW; 
242            priority < G_THREAD_PRIORITY_URGENT + 1; priority++)
243         unused_thread_queue[priority] = g_async_queue_new ();
244     }
245
246   if (retval->pool.exclusive)
247     {
248       g_async_queue_lock (retval->queue);
249   
250       while (retval->num_threads < retval->max_threads)
251         {
252           GError *local_error = NULL;
253           g_thread_pool_start_thread (retval, &local_error);
254           if (local_error)
255             {
256               g_propagate_error (error, local_error);
257               break;
258             }
259         }
260
261       g_async_queue_unlock (retval->queue);
262     }
263
264   return (GThreadPool*) retval;
265 }
266
267 void 
268 g_thread_pool_push (GThreadPool     *pool,
269                     gpointer         data,
270                     GError         **error)
271 {
272   GRealThreadPool *real = (GRealThreadPool*) pool;
273
274   g_return_if_fail (real);
275
276   g_async_queue_lock (real->queue);
277   
278   if (!real->running)
279     {
280       g_async_queue_unlock (real->queue);
281       g_return_if_fail (real->running);
282     }
283
284   if (!pool->exclusive && g_async_queue_length_unlocked (real->queue) >= 0)
285     /* No thread is waiting in the queue */
286     g_thread_pool_start_thread (real, error);
287
288   g_async_queue_push_unlocked (real->queue, data);
289   g_async_queue_unlock (real->queue);
290 }
291
292 void
293 g_thread_pool_set_max_threads (GThreadPool     *pool,
294                                gint             max_threads,
295                                GError         **error)
296 {
297   GRealThreadPool *real = (GRealThreadPool*) pool;
298   gint to_start;
299
300   g_return_if_fail (real);
301   g_return_if_fail (real->running);
302   g_return_if_fail (!real->pool.exclusive || max_threads != -1);
303   g_return_if_fail (max_threads >= -1);
304
305   g_async_queue_lock (real->queue);
306
307   real->max_threads = max_threads;
308   
309   if (pool->exclusive)
310     to_start = real->max_threads - real->num_threads;
311   else
312     to_start = g_async_queue_length_unlocked (real->queue);
313   
314   for ( ; to_start > 0; to_start--)
315     {
316       GError *local_error = NULL;
317       g_thread_pool_start_thread (real, &local_error);
318       if (local_error)
319         {
320           g_propagate_error (error, local_error);
321           break;
322         }
323     }
324    
325   g_async_queue_unlock (real->queue);
326 }
327
328 gint
329 g_thread_pool_get_max_threads (GThreadPool     *pool)
330 {
331   GRealThreadPool *real = (GRealThreadPool*) pool;
332   gint retval;
333
334   g_return_val_if_fail (real, 0);
335   g_return_val_if_fail (real->running, 0);
336
337   g_async_queue_lock (real->queue);
338
339   retval = real->max_threads;
340     
341   g_async_queue_unlock (real->queue);
342
343   return retval;
344 }
345
346 guint
347 g_thread_pool_get_num_threads (GThreadPool     *pool)
348 {
349   GRealThreadPool *real = (GRealThreadPool*) pool;
350   guint retval;
351
352   g_return_val_if_fail (real, 0);
353   g_return_val_if_fail (real->running, 0);
354
355   g_async_queue_lock (real->queue);
356
357   retval = real->num_threads;
358     
359   g_async_queue_unlock (real->queue);
360
361   return retval;
362 }
363
364 guint
365 g_thread_pool_unprocessed (GThreadPool     *pool)
366 {
367   GRealThreadPool *real = (GRealThreadPool*) pool;
368   gint unprocessed;
369
370   g_return_val_if_fail (real, 0);
371   g_return_val_if_fail (real->running, 0);
372
373   unprocessed = g_async_queue_length (real->queue);
374
375   return MAX (unprocessed, 0);
376 }
377
378 void
379 g_thread_pool_free (GThreadPool     *pool,
380                     gboolean         immediate,
381                     gboolean         wait)
382 {
383   GRealThreadPool *real = (GRealThreadPool*) pool;
384
385   g_return_if_fail (real);
386   g_return_if_fail (real->running);
387   /* It there's no thread allowed here, there is not much sense in
388    * not stopping this pool immediatly, when it's not empty */
389   g_return_if_fail (immediate || real->max_threads != 0 || 
390                     g_async_queue_length (real->queue) == 0);
391
392   g_async_queue_lock (real->queue);
393
394   real->running = FALSE;
395   real->immediate = immediate;
396   real->waiting = wait;
397
398   if (wait)
399     {
400       g_mutex_lock (inform_mutex);
401       while (g_async_queue_length_unlocked (real->queue) != -real->num_threads)
402         {
403           g_async_queue_unlock (real->queue); 
404           g_cond_wait (inform_cond, inform_mutex); 
405           g_async_queue_lock (real->queue); 
406         }
407       g_mutex_unlock (inform_mutex); 
408     }
409
410   if (g_async_queue_length_unlocked (real->queue) == -real->num_threads)
411     {
412       /* No thread is currently doing something (and nothing is left
413        * to process in the queue) */
414       if (real->num_threads == 0) /* No threads left, we clean up */
415         {
416           g_async_queue_unlock (real->queue);
417           g_thread_pool_free_internal (real);
418           return;
419         }
420
421       g_thread_pool_wakeup_and_stop_all (real);
422     }
423   
424   real->waiting = FALSE; /* The last thread should cleanup the pool */
425   g_async_queue_unlock (real->queue);
426 }
427
428 static void
429 g_thread_pool_free_internal (GRealThreadPool* pool)
430 {
431   g_return_if_fail (pool);
432   g_return_if_fail (!pool->running);
433   g_return_if_fail (pool->num_threads == 0);
434
435   g_async_queue_unref (pool->queue);
436
437   g_free (pool);
438 }
439
440 static void
441 g_thread_pool_wakeup_and_stop_all (GRealThreadPool* pool)
442 {
443   guint i;
444   
445   g_return_if_fail (pool);
446   g_return_if_fail (!pool->running);
447   g_return_if_fail (pool->num_threads != 0);
448   g_return_if_fail (g_async_queue_length_unlocked (pool->queue) == 
449                     -pool->num_threads);
450
451   pool->immediate = TRUE; 
452   for (i = 0; i < pool->num_threads; i++)
453     g_async_queue_push_unlocked (pool->queue, GUINT_TO_POINTER (1));
454 }
455
456 void
457 g_thread_pool_set_max_unused_threads (gint max_threads)
458 {
459   g_return_if_fail (max_threads >= -1);  
460
461   G_LOCK (unused_threads);
462   
463   max_unused_threads = max_threads;
464
465   if (max_unused_threads < unused_threads && max_unused_threads != -1)
466     {
467       guint close_down_num = unused_threads - max_unused_threads;
468       GThreadPriority priority;
469
470       while (close_down_num > 0)
471         {
472           guint old_close_down_num = close_down_num;
473           for (priority = G_THREAD_PRIORITY_LOW; 
474                priority < G_THREAD_PRIORITY_URGENT + 1 && close_down_num > 0; 
475                priority++)
476             {
477               GAsyncQueue *queue = unused_thread_queue[priority];
478               g_async_queue_lock (queue);
479               
480               if (g_async_queue_length_unlocked (queue) < 0)
481                 {
482                   g_async_queue_push_unlocked (queue, 
483                                                stop_this_thread_marker);
484                   close_down_num--;
485                 }
486               
487               g_async_queue_unlock (queue);
488             }
489
490           /* Just to make sure, there are no counting problems */
491           g_assert (old_close_down_num != close_down_num);
492         }
493     }
494     
495   G_UNLOCK (unused_threads);
496 }
497
498 gint
499 g_thread_pool_get_max_unused_threads (void)
500 {
501   gint retval;
502   
503   G_LOCK (unused_threads);
504   retval = max_unused_threads;
505   G_UNLOCK (unused_threads);
506
507   return retval;
508 }
509
510 guint g_thread_pool_get_num_unused_threads (void)
511 {
512   guint retval;
513   
514   G_LOCK (unused_threads);
515   retval = unused_threads;
516   G_UNLOCK (unused_threads);
517
518   return retval;
519 }
520
521 void g_thread_pool_stop_unused_threads (void)
522
523   guint oldval = g_thread_pool_get_max_unused_threads ();
524   g_thread_pool_set_max_unused_threads (0);
525   g_thread_pool_set_max_unused_threads (oldval);
526 }