d57a9cb4bc60245255cbc12f9bc29eb4bbccc4a8
[platform/upstream/glib.git] / glib / gthread-posix.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * gthread.c: posix thread system implementation
5  * Copyright 1998 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  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
25  * file for a list of people on the GLib Team.  See the ChangeLog
26  * files for a list of changes.  These files are distributed with
27  * GLib at ftp://ftp.gtk.org/pub/gtk/.
28  */
29
30 /* The GMutex, GCond and GPrivate implementations in this file are some
31  * of the lowest-level code in GLib.  All other parts of GLib (messages,
32  * memory, slices, etc) assume that they can freely use these facilities
33  * without risking recursion.
34  *
35  * As such, these functions are NOT permitted to call any other part of
36  * GLib.
37  *
38  * The thread manipulation functions (create, exit, join, etc.) have
39  * more freedom -- they can do as they please.
40  */
41
42 #include "config.h"
43
44 #include "gthread.h"
45
46 #include "gthreadprivate.h"
47 #include "gslice.h"
48 #include "gmessages.h"
49 #include "gstrfuncs.h"
50
51 #include <stdlib.h>
52 #include <stdio.h>
53 #include <string.h>
54 #include <errno.h>
55 #include <pthread.h>
56
57 #ifdef HAVE_SYS_TIME_H
58 # include <sys/time.h>
59 #endif
60 #ifdef HAVE_UNISTD_H
61 # include <unistd.h>
62 #endif
63 #ifdef HAVE_SCHED_H
64 #include <sched.h>
65 #endif
66 #ifdef HAVE_SYS_PRCTL_H
67 #include <sys/prctl.h>
68 #endif
69 #ifdef G_OS_WIN32
70 #include <windows.h>
71 #endif
72
73 static void
74 g_thread_abort (gint         status,
75                 const gchar *function)
76 {
77   fprintf (stderr, "GLib (gthread-posix.c): Unexpected error from C library during '%s': %s.  Aborting.\n",
78            function, strerror (status));
79   abort ();
80 }
81
82 /* {{{1 GMutex */
83
84 static pthread_mutex_t *
85 g_mutex_impl_new (void)
86 {
87   pthread_mutexattr_t *pattr = NULL;
88   pthread_mutex_t *mutex;
89   gint status;
90
91   mutex = malloc (sizeof (pthread_mutex_t));
92   if G_UNLIKELY (mutex == NULL)
93     g_thread_abort (errno, "malloc");
94
95 #ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
96   {
97     pthread_mutexattr_t attr;
98     pthread_mutexattr_init (&attr);
99     pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_ADAPTIVE_NP);
100     pattr = &attr;
101   }
102 #endif
103
104   if G_UNLIKELY ((status = pthread_mutex_init (mutex, pattr)) != 0)
105     g_thread_abort (status, "pthread_mutex_init");
106
107 #ifdef PTHREAD_ADAPTIVE_MUTEX_NP
108   pthread_mutexattr_destroy (&attr);
109 #endif
110
111   return mutex;
112 }
113
114 static void
115 g_mutex_impl_free (pthread_mutex_t *mutex)
116 {
117   pthread_mutex_destroy (mutex);
118   free (mutex);
119 }
120
121 static pthread_mutex_t *
122 g_mutex_get_impl (GMutex *mutex)
123 {
124   pthread_mutex_t *impl = g_atomic_pointer_get (&mutex->p);
125
126   if G_UNLIKELY (impl == NULL)
127     {
128       impl = g_mutex_impl_new ();
129       if (!g_atomic_pointer_compare_and_exchange (&mutex->p, NULL, impl))
130         g_mutex_impl_free (impl);
131       impl = mutex->p;
132     }
133
134   return impl;
135 }
136
137
138 /**
139  * g_mutex_init:
140  * @mutex: an uninitialized #GMutex
141  *
142  * Initializes a #GMutex so that it can be used.
143  *
144  * This function is useful to initialize a mutex that has been
145  * allocated on the stack, or as part of a larger structure.
146  * It is not necessary to initialize a mutex that has been
147  * statically allocated.
148  *
149  * |[
150  *   typedef struct {
151  *     GMutex m;
152  *     ...
153  *   } Blob;
154  *
155  * Blob *b;
156  *
157  * b = g_new (Blob, 1);
158  * g_mutex_init (&b->m);
159  * ]|
160  *
161  * To undo the effect of g_mutex_init() when a mutex is no longer
162  * needed, use g_mutex_clear().
163  *
164  * Calling g_mutex_init() on an already initialized #GMutex leads
165  * to undefined behaviour.
166  *
167  * Since: 2.32
168  */
169 void
170 g_mutex_init (GMutex *mutex)
171 {
172   mutex->p = g_mutex_impl_new ();
173 }
174
175 /**
176  * g_mutex_clear:
177  * @mutex: an initialized #GMutex
178  *
179  * Frees the resources allocated to a mutex with g_mutex_init().
180  *
181  * This function should not be used with a #GMutex that has been
182  * statically allocated.
183  *
184  * Calling g_mutex_clear() on a locked mutex leads to undefined
185  * behaviour.
186  *
187  * Since: 2.32
188  */
189 void
190 g_mutex_clear (GMutex *mutex)
191 {
192   g_mutex_impl_free (mutex->p);
193   mutex->p = NULL;
194 }
195
196 /**
197  * g_mutex_lock:
198  * @mutex: a #GMutex
199  *
200  * Locks @mutex. If @mutex is already locked by another thread, the
201  * current thread will block until @mutex is unlocked by the other
202  * thread.
203  *
204  * <note>#GMutex is neither guaranteed to be recursive nor to be
205  * non-recursive.  As such, calling g_mutex_lock() on a #GMutex that has
206  * already been locked by the same thread results in undefined behaviour
207  * (including but not limited to deadlocks).</note>
208  */
209 void
210 g_mutex_lock (GMutex *mutex)
211 {
212   gint status;
213
214   if G_UNLIKELY ((status = pthread_mutex_lock (g_mutex_get_impl (mutex))) != 0)
215     g_thread_abort (status, "pthread_mutex_lock");
216 }
217
218 /**
219  * g_mutex_unlock:
220  * @mutex: a #GMutex
221  *
222  * Unlocks @mutex. If another thread is blocked in a g_mutex_lock()
223  * call for @mutex, it will become unblocked and can lock @mutex itself.
224  *
225  * Calling g_mutex_unlock() on a mutex that is not locked by the
226  * current thread leads to undefined behaviour.
227  */
228 void
229 g_mutex_unlock (GMutex *mutex)
230 {
231   gint status;
232
233   if G_UNLIKELY ((status = pthread_mutex_unlock (g_mutex_get_impl (mutex))) != 0)
234     g_thread_abort (status, "pthread_mutex_unlock");
235 }
236
237 /**
238  * g_mutex_trylock:
239  * @mutex: a #GMutex
240  *
241  * Tries to lock @mutex. If @mutex is already locked by another thread,
242  * it immediately returns %FALSE. Otherwise it locks @mutex and returns
243  * %TRUE.
244  *
245  * <note>#GMutex is neither guaranteed to be recursive nor to be
246  * non-recursive.  As such, calling g_mutex_lock() on a #GMutex that has
247  * already been locked by the same thread results in undefined behaviour
248  * (including but not limited to deadlocks or arbitrary return values).
249  * </note>
250
251  * Returns: %TRUE if @mutex could be locked
252  */
253 gboolean
254 g_mutex_trylock (GMutex *mutex)
255 {
256   gint status;
257
258   if G_LIKELY ((status = pthread_mutex_trylock (g_mutex_get_impl (mutex))) == 0)
259     return TRUE;
260
261   if G_UNLIKELY (status != EBUSY)
262     g_thread_abort (status, "pthread_mutex_trylock");
263
264   return FALSE;
265 }
266
267 /* {{{1 GRecMutex */
268
269 static pthread_mutex_t *
270 g_rec_mutex_impl_new (void)
271 {
272   pthread_mutexattr_t attr;
273   pthread_mutex_t *mutex;
274
275   mutex = g_slice_new (pthread_mutex_t);
276   pthread_mutexattr_init (&attr);
277   pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
278   pthread_mutex_init (mutex, &attr);
279   pthread_mutexattr_destroy (&attr);
280
281   return mutex;
282 }
283
284 static void
285 g_rec_mutex_impl_free (pthread_mutex_t *mutex)
286 {
287   pthread_mutex_destroy (mutex);
288   g_slice_free (pthread_mutex_t, mutex);
289 }
290
291 static pthread_mutex_t *
292 g_rec_mutex_get_impl (GRecMutex *rec_mutex)
293 {
294   pthread_mutex_t *impl = g_atomic_pointer_get (&rec_mutex->p);
295
296   if G_UNLIKELY (impl == NULL)
297     {
298       impl = g_rec_mutex_impl_new ();
299       if (!g_atomic_pointer_compare_and_exchange (&rec_mutex->p, NULL, impl))
300         g_rec_mutex_impl_free (impl);
301       impl = rec_mutex->p;
302     }
303
304   return impl;
305 }
306
307 /**
308  * g_rec_mutex_init:
309  * @rec_mutex: an uninitialized #GRecMutex
310  *
311  * Initializes a #GRecMutex so that it can be used.
312  *
313  * This function is useful to initialize a recursive mutex
314  * that has been allocated on the stack, or as part of a larger
315  * structure.
316  *
317  * It is not necessary to initialise a recursive mutex that has been
318  * statically allocated.
319  *
320  * |[
321  *   typedef struct {
322  *     GRecMutex m;
323  *     ...
324  *   } Blob;
325  *
326  * Blob *b;
327  *
328  * b = g_new (Blob, 1);
329  * g_rec_mutex_init (&b->m);
330  * ]|
331  *
332  * Calling g_rec_mutex_init() on an already initialized #GRecMutex
333  * leads to undefined behaviour.
334  *
335  * To undo the effect of g_rec_mutex_init() when a recursive mutex
336  * is no longer needed, use g_rec_mutex_clear().
337  *
338  * Since: 2.32
339  */
340 void
341 g_rec_mutex_init (GRecMutex *rec_mutex)
342 {
343   rec_mutex->p = g_rec_mutex_impl_new ();
344 }
345
346 /**
347  * g_rec_mutex_clear:
348  * @rec_mutex: an initialized #GRecMutex
349  *
350  * Frees the resources allocated to a recursive mutex with
351  * g_rec_mutex_init().
352  *
353  * This function should not be used with a #GRecMutex that has been
354  * statically allocated.
355  *
356  * Calling g_rec_mutex_clear() on a locked recursive mutex leads
357  * to undefined behaviour.
358  *
359  * Sine: 2.32
360  */
361 void
362 g_rec_mutex_clear (GRecMutex *rec_mutex)
363 {
364   g_rec_mutex_impl_free (rec_mutex->p);
365 }
366
367 /**
368  * g_rec_mutex_lock:
369  * @rec_mutex: a #GRecMutex
370  *
371  * Locks @rec_mutex. If @rec_mutex is already locked by another
372  * thread, the current thread will block until @rec_mutex is
373  * unlocked by the other thread. If @rec_mutex is already locked
374  * by the current thread, the 'lock count' of @rec_mutex is increased.
375  * The mutex will only become available again when it is unlocked
376  * as many times as it has been locked.
377  *
378  * Since: 2.32
379  */
380 void
381 g_rec_mutex_lock (GRecMutex *mutex)
382 {
383   pthread_mutex_lock (g_rec_mutex_get_impl (mutex));
384 }
385
386 /**
387  * g_rec_mutex_unlock:
388  * @rec_mutex: a #GRecMutex
389  *
390  * Unlocks @rec_mutex. If another thread is blocked in a
391  * g_rec_mutex_lock() call for @rec_mutex, it will become unblocked
392  * and can lock @rec_mutex itself.
393  *
394  * Calling g_rec_mutex_unlock() on a recursive mutex that is not
395  * locked by the current thread leads to undefined behaviour.
396  *
397  * Since: 2.32
398  */
399 void
400 g_rec_mutex_unlock (GRecMutex *rec_mutex)
401 {
402   pthread_mutex_unlock (rec_mutex->p);
403 }
404
405 /**
406  * g_rec_mutex_trylock:
407  * @rec_mutex: a #GRecMutex
408  *
409  * Tries to lock @rec_mutex. If @rec_mutex is already locked
410  * by another thread, it immediately returns %FALSE. Otherwise
411  * it locks @rec_mutex and returns %TRUE.
412  *
413  * Returns: %TRUE if @rec_mutex could be locked
414  *
415  * Since: 2.32
416  */
417 gboolean
418 g_rec_mutex_trylock (GRecMutex *rec_mutex)
419 {
420   if (pthread_mutex_trylock (g_rec_mutex_get_impl (rec_mutex)) != 0)
421     return FALSE;
422
423   return TRUE;
424 }
425
426 /* {{{1 GRWLock */
427
428 static pthread_rwlock_t *
429 g_rw_lock_impl_new (void)
430 {
431   pthread_rwlock_t *rwlock;
432   gint status;
433
434   rwlock = malloc (sizeof (pthread_rwlock_t));
435   if G_UNLIKELY (rwlock == NULL)
436     g_thread_abort (errno, "malloc");
437
438   if G_UNLIKELY ((status = pthread_rwlock_init (rwlock, NULL)) != 0)
439     g_thread_abort (status, "pthread_rwlock_init");
440
441   return rwlock;
442 }
443
444 static void
445 g_rw_lock_impl_free (pthread_rwlock_t *rwlock)
446 {
447   pthread_rwlock_destroy (rwlock);
448   free (rwlock);
449 }
450
451 static pthread_rwlock_t *
452 g_rw_lock_get_impl (GRWLock *lock)
453 {
454   pthread_rwlock_t *impl = g_atomic_pointer_get (&lock->p);
455
456   if G_UNLIKELY (impl == NULL)
457     {
458       impl = g_rw_lock_impl_new ();
459       if (!g_atomic_pointer_compare_and_exchange (&lock->p, NULL, impl))
460         g_rw_lock_impl_free (impl);
461       impl = lock->p;
462     }
463
464   return impl;
465 }
466
467 /**
468  * g_rw_lock_init:
469  * @rw_lock: an uninitialized #GRWLock
470  *
471  * Initializes a #GRWLock so that it can be used.
472  *
473  * This function is useful to initialize a lock that has been
474  * allocated on the stack, or as part of a larger structure.  It is not
475  * necessary to initialise a reader-writer lock that has been statically
476  * allocated.
477  *
478  * |[
479  *   typedef struct {
480  *     GRWLock l;
481  *     ...
482  *   } Blob;
483  *
484  * Blob *b;
485  *
486  * b = g_new (Blob, 1);
487  * g_rw_lock_init (&b->l);
488  * ]|
489  *
490  * To undo the effect of g_rw_lock_init() when a lock is no longer
491  * needed, use g_rw_lock_clear().
492  *
493  * Calling g_rw_lock_init() on an already initialized #GRWLock leads
494  * to undefined behaviour.
495  *
496  * Since: 2.32
497  */
498 void
499 g_rw_lock_init (GRWLock *rw_lock)
500 {
501   rw_lock->p = g_rw_lock_impl_new ();
502 }
503
504 /**
505  * g_rw_lock_clear:
506  * @rw_lock: an initialized #GRWLock
507  *
508  * Frees the resources allocated to a lock with g_rw_lock_init().
509  *
510  * This function should not be used with a #GRWLock that has been
511  * statically allocated.
512  *
513  * Calling g_rw_lock_clear() when any thread holds the lock
514  * leads to undefined behaviour.
515  *
516  * Sine: 2.32
517  */
518 void
519 g_rw_lock_clear (GRWLock *rw_lock)
520 {
521   g_rw_lock_impl_free (rw_lock->p);
522 }
523
524 /**
525  * g_rw_lock_writer_lock:
526  * @rw_lock: a #GRWLock
527  *
528  * Obtain a write lock on @rw_lock. If any thread already holds
529  * a read or write lock on @rw_lock, the current thread will block
530  * until all other threads have dropped their locks on @rw_lock.
531  *
532  * Since: 2.32
533  */
534 void
535 g_rw_lock_writer_lock (GRWLock *rw_lock)
536 {
537   pthread_rwlock_wrlock (g_rw_lock_get_impl (rw_lock));
538 }
539
540 /**
541  * g_rw_lock_writer_trylock:
542  * @rw_lock: a #GRWLock
543  *
544  * Tries to obtain a write lock on @rw_lock. If any other thread holds
545  * a read or write lock on @rw_lock, it immediately returns %FALSE.
546  * Otherwise it locks @rw_lock and returns %TRUE.
547  *
548  * Returns: %TRUE if @rw_lock could be locked
549  *
550  * Since: 2.32
551  */
552 gboolean
553 g_rw_lock_writer_trylock (GRWLock *rw_lock)
554 {
555   if (pthread_rwlock_trywrlock (g_rw_lock_get_impl (rw_lock)) != 0)
556     return FALSE;
557
558   return TRUE;
559 }
560
561 /**
562  * g_rw_lock_writer_unlock:
563  * @rw_lock: a #GRWLock
564  *
565  * Release a write lock on @rw_lock.
566  *
567  * Calling g_rw_lock_writer_unlock() on a lock that is not held
568  * by the current thread leads to undefined behaviour.
569  *
570  * Since: 2.32
571  */
572 void
573 g_rw_lock_writer_unlock (GRWLock *rw_lock)
574 {
575   pthread_rwlock_unlock (g_rw_lock_get_impl (rw_lock));
576 }
577
578 /**
579  * g_rw_lock_reader_lock:
580  * @rw_lock: a #GRWLock
581  *
582  * Obtain a read lock on @rw_lock. If another thread currently holds
583  * the write lock on @rw_lock or blocks waiting for it, the current
584  * thread will block. Read locks can be taken recursively.
585  *
586  * It is implementation-defined how many threads are allowed to
587  * hold read locks on the same lock simultaneously.
588  *
589  * Since: 2.32
590  */
591 void
592 g_rw_lock_reader_lock (GRWLock *rw_lock)
593 {
594   pthread_rwlock_rdlock (g_rw_lock_get_impl (rw_lock));
595 }
596
597 /**
598  * g_rw_lock_reader_trylock:
599  * @rw_lock: a #GRWLock
600  *
601  * Tries to obtain a read lock on @rw_lock and returns %TRUE if
602  * the read lock was successfully obtained. Otherwise it
603  * returns %FALSE.
604  *
605  * Returns: %TRUE if @rw_lock could be locked
606  *
607  * Since: 2.32
608  */
609 gboolean
610 g_rw_lock_reader_trylock (GRWLock *rw_lock)
611 {
612   if (pthread_rwlock_tryrdlock (g_rw_lock_get_impl (rw_lock)) != 0)
613     return FALSE;
614
615   return TRUE;
616 }
617
618 /**
619  * g_rw_lock_reader_unlock:
620  * @rw_lock: a #GRWLock
621  *
622  * Release a read lock on @rw_lock.
623  *
624  * Calling g_rw_lock_reader_unlock() on a lock that is not held
625  * by the current thread leads to undefined behaviour.
626  *
627  * Since: 2.32
628  */
629 void
630 g_rw_lock_reader_unlock (GRWLock *rw_lock)
631 {
632   pthread_rwlock_unlock (g_rw_lock_get_impl (rw_lock));
633 }
634
635 /* {{{1 GCond */
636
637 static pthread_cond_t *
638 g_cond_impl_new (void)
639 {
640   pthread_condattr_t attr;
641   pthread_cond_t *cond;
642   gint status;
643
644   pthread_condattr_init (&attr);
645 #if defined (HAVE_PTHREAD_CONDATTR_SETCLOCK) && defined (CLOCK_MONOTONIC)
646   pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
647 #endif
648
649   cond = malloc (sizeof (pthread_cond_t));
650   if G_UNLIKELY (cond == NULL)
651     g_thread_abort (errno, "malloc");
652
653   if G_UNLIKELY ((status = pthread_cond_init (cond, &attr)) != 0)
654     g_thread_abort (status, "pthread_cond_init");
655
656   pthread_condattr_destroy (&attr);
657
658   return cond;
659 }
660
661 static void
662 g_cond_impl_free (pthread_cond_t *cond)
663 {
664   pthread_cond_destroy (cond);
665   free (cond);
666 }
667
668 static pthread_cond_t *
669 g_cond_get_impl (GCond *cond)
670 {
671   pthread_cond_t *impl = g_atomic_pointer_get (&cond->p);
672
673   if G_UNLIKELY (impl == NULL)
674     {
675       impl = g_cond_impl_new ();
676       if (!g_atomic_pointer_compare_and_exchange (&cond->p, NULL, impl))
677         g_cond_impl_free (impl);
678       impl = cond->p;
679     }
680
681   return impl;
682 }
683
684 /**
685  * g_cond_init:
686  * @cond: an uninitialized #GCond
687  *
688  * Initialises a #GCond so that it can be used.
689  *
690  * This function is useful to initialise a #GCond that has been
691  * allocated as part of a larger structure.  It is not necessary to
692  * initialise a #GCond that has been statically allocated.
693  *
694  * To undo the effect of g_cond_init() when a #GCond is no longer
695  * needed, use g_cond_clear().
696  *
697  * Calling g_cond_init() on an already-initialised #GCond leads
698  * to undefined behaviour.
699  *
700  * Since: 2.32
701  */
702 void
703 g_cond_init (GCond *cond)
704 {
705   cond->p = g_cond_impl_new ();
706 }
707
708 /**
709  * g_cond_clear:
710  * @cond: an initialised #GCond
711  *
712  * Frees the resources allocated to a #GCond with g_cond_init().
713  *
714  * This function should not be used with a #GCond that has been
715  * statically allocated.
716  *
717  * Calling g_cond_clear() for a #GCond on which threads are
718  * blocking leads to undefined behaviour.
719  *
720  * Since: 2.32
721  */
722 void
723 g_cond_clear (GCond *cond)
724 {
725   g_cond_impl_free (cond->p);
726 }
727
728 /**
729  * g_cond_wait:
730  * @cond: a #GCond
731  * @mutex: a #GMutex that is currently locked
732  *
733  * Atomically releases @mutex and waits until @cond is signalled.
734  * When this function returns, @mutex is locked again and owned by the
735  * calling thread.
736  *
737  * When using condition variables, it is possible that a spurious wakeup
738  * may occur (ie: g_cond_wait() returns even though g_cond_signal() was
739  * not called).  It's also possible that a stolen wakeup may occur.
740  * This is when g_cond_signal() is called, but another thread acquires
741  * @mutex before this thread and modifies the state of the program in
742  * such a way that when g_cond_wait() is able to return, the expected
743  * condition is no longer met.
744  *
745  * For this reason, g_cond_wait() must always be used in a loop.  See
746  * the documentation for #GCond for a complete example.
747  **/
748 void
749 g_cond_wait (GCond  *cond,
750              GMutex *mutex)
751 {
752   gint status;
753
754   if G_UNLIKELY ((status = pthread_cond_wait (g_cond_get_impl (cond), g_mutex_get_impl (mutex))) != 0)
755     g_thread_abort (status, "pthread_cond_wait");
756 }
757
758 /**
759  * g_cond_signal:
760  * @cond: a #GCond
761  *
762  * If threads are waiting for @cond, at least one of them is unblocked.
763  * If no threads are waiting for @cond, this function has no effect.
764  * It is good practice to hold the same lock as the waiting thread
765  * while calling this function, though not required.
766  */
767 void
768 g_cond_signal (GCond *cond)
769 {
770   gint status;
771
772   if G_UNLIKELY ((status = pthread_cond_signal (g_cond_get_impl (cond))) != 0)
773     g_thread_abort (status, "pthread_cond_signal");
774 }
775
776 /**
777  * g_cond_broadcast:
778  * @cond: a #GCond
779  *
780  * If threads are waiting for @cond, all of them are unblocked.
781  * If no threads are waiting for @cond, this function has no effect.
782  * It is good practice to lock the same mutex as the waiting threads
783  * while calling this function, though not required.
784  */
785 void
786 g_cond_broadcast (GCond *cond)
787 {
788   gint status;
789
790   if G_UNLIKELY ((status = pthread_cond_broadcast (g_cond_get_impl (cond))) != 0)
791     g_thread_abort (status, "pthread_cond_broadcast");
792 }
793
794 /**
795  * g_cond_wait_until:
796  * @cond: a #GCond
797  * @mutex: a #GMutex that is currently locked
798  * @end_time: the monotonic time to wait until
799  *
800  * Waits until either @cond is signalled or @end_time has passed.
801  *
802  * As with g_cond_wait() it is possible that a spurious or stolen wakeup
803  * could occur.  For that reason, waiting on a condition variable should
804  * always be in a loop, based on an explicitly-checked predicate.
805  *
806  * %TRUE is returned if the condition variable was signalled (or in the
807  * case of a spurious wakeup).  %FALSE is returned if @end_time has
808  * passed.
809  *
810  * The following code shows how to correctly perform a timed wait on a
811  * condition variable (extended the example presented in the
812  * documentation for #GCond):
813  *
814  * |[
815  * gpointer
816  * pop_data_timed (void)
817  * {
818  *   gint64 end_time;
819  *   gpointer data;
820  *
821  *   g_mutex_lock (&data_mutex);
822  *
823  *   end_time = g_get_monotonic_time () + 5 * G_TIME_SPAN_SECOND;
824  *   while (!current_data)
825  *     if (!g_cond_wait_until (&data_cond, &data_mutex, end_time))
826  *       {
827  *         // timeout has passed.
828  *         g_mutex_unlock (&data_mutex);
829  *         return NULL;
830  *       }
831  *
832  *   // there is data for us
833  *   data = current_data;
834  *   current_data = NULL;
835  *
836  *   g_mutex_unlock (&data_mutex);
837  *
838  *   return data;
839  * }
840  * ]|
841  *
842  * Notice that the end time is calculated once, before entering the
843  * loop and reused.  This is the motivation behind the use of absolute
844  * time on this API -- if a relative time of 5 seconds were passed
845  * directly to the call and a spurious wakeup occurred, the program would
846  * have to start over waiting again (which would lead to a total wait
847  * time of more than 5 seconds).
848  *
849  * Returns: %TRUE on a signal, %FALSE on a timeout
850  * Since: 2.32
851  **/
852 gboolean
853 g_cond_wait_until (GCond  *cond,
854                    GMutex *mutex,
855                    gint64  end_time)
856 {
857   struct timespec ts;
858   gint status;
859
860   ts.tv_sec = end_time / 1000000;
861   ts.tv_nsec = (end_time % 1000000) * 1000;
862
863   if ((status = pthread_cond_timedwait (g_cond_get_impl (cond), g_mutex_get_impl (mutex), &ts)) == 0)
864     return TRUE;
865
866   if G_UNLIKELY (status != ETIMEDOUT)
867     g_thread_abort (status, "pthread_cond_timedwait");
868
869   return FALSE;
870 }
871
872 /* {{{1 GPrivate */
873
874 /**
875  * GPrivate:
876  *
877  * The #GPrivate struct is an opaque data structure to represent a
878  * thread-local data key. It is approximately equivalent to the
879  * pthread_setspecific()/pthread_getspecific() APIs on POSIX and to
880  * TlsSetValue()/TlsGetValue() on Windows.
881  *
882  * If you don't already know why you might want this functionality,
883  * then you probably don't need it.
884  *
885  * #GPrivate is a very limited resource (as far as 128 per program,
886  * shared between all libraries). It is also not possible to destroy a
887  * #GPrivate after it has been used. As such, it is only ever acceptable
888  * to use #GPrivate in static scope, and even then sparingly so.
889  *
890  * See G_PRIVATE_INIT() for a couple of examples.
891  *
892  * The #GPrivate structure should be considered opaque.  It should only
893  * be accessed via the <function>g_private_</function> functions.
894  */
895
896 /**
897  * G_PRIVATE_INIT:
898  * @notify: a #GDestroyNotify
899  *
900  * A macro to assist with the static initialisation of a #GPrivate.
901  *
902  * This macro is useful for the case that a #GDestroyNotify function
903  * should be associated the key.  This is needed when the key will be
904  * used to point at memory that should be deallocated when the thread
905  * exits.
906  *
907  * Additionally, the #GDestroyNotify will also be called on the previous
908  * value stored in the key when g_private_replace() is used.
909  *
910  * If no #GDestroyNotify is needed, then use of this macro is not
911  * required -- if the #GPrivate is declared in static scope then it will
912  * be properly initialised by default (ie: to all zeros).  See the
913  * examples below.
914  *
915  * |[
916  * static GPrivate name_key = G_PRIVATE_INIT (g_free);
917  *
918  * // return value should not be freed
919  * const gchar *
920  * get_local_name (void)
921  * {
922  *   return g_private_get (&name_key);
923  * }
924  *
925  * void
926  * set_local_name (const gchar *name)
927  * {
928  *   g_private_replace (&name_key, g_strdup (name));
929  * }
930  *
931  *
932  * static GPrivate count_key;   // no free function
933  *
934  * gint
935  * get_local_count (void)
936  * {
937  *   return GPOINTER_TO_INT (g_private_get (&count_key));
938  * }
939  *
940  * void
941  * set_local_count (gint count)
942  * {
943  *   g_private_set (&count_key, GINT_TO_POINTER (count));
944  * }
945  * ]|
946  *
947  * Since: 2.32
948  **/
949
950 static pthread_key_t *
951 g_private_impl_new (GDestroyNotify notify)
952 {
953   pthread_key_t *key;
954   gint status;
955
956   key = malloc (sizeof (pthread_key_t));
957   if G_UNLIKELY (key == NULL)
958     g_thread_abort (errno, "malloc");
959   status = pthread_key_create (key, notify);
960   if G_UNLIKELY (status != 0)
961     g_thread_abort (status, "pthread_key_create");
962
963   return key;
964 }
965
966 static void
967 g_private_impl_free (pthread_key_t *key)
968 {
969   gint status;
970
971   status = pthread_key_delete (*key);
972   if G_UNLIKELY (status != 0)
973     g_thread_abort (status, "pthread_key_delete");
974   free (key);
975 }
976
977 static pthread_key_t *
978 g_private_get_impl (GPrivate *key)
979 {
980   pthread_key_t *impl = g_atomic_pointer_get (&key->p);
981
982   if G_UNLIKELY (impl == NULL)
983     {
984       impl = g_private_impl_new (key->notify);
985       if (!g_atomic_pointer_compare_and_exchange (&key->p, NULL, impl))
986         {
987           g_private_impl_free (impl);
988           impl = key->p;
989         }
990     }
991
992   return impl;
993 }
994
995 /**
996  * g_private_get:
997  * @key: a #GPrivate
998  *
999  * Returns the current value of the thread local variable @key.
1000  *
1001  * If the value has not yet been set in this thread, %NULL is returned.
1002  * Values are never copied between threads (when a new thread is
1003  * created, for example).
1004  *
1005  * Returns: the thread-local value
1006  */
1007 gpointer
1008 g_private_get (GPrivate *key)
1009 {
1010   /* quote POSIX: No errors are returned from pthread_getspecific(). */
1011   return pthread_getspecific (*g_private_get_impl (key));
1012 }
1013
1014 /**
1015  * g_private_set:
1016  * @key: a #GPrivate
1017  * @value: the new value
1018  *
1019  * Sets the thread local variable @key to have the value @value in the
1020  * current thread.
1021  *
1022  * This function differs from g_private_replace() in the following way:
1023  * the #GDestroyNotify for @key is not called on the old value.
1024  */
1025 void
1026 g_private_set (GPrivate *key,
1027                gpointer  value)
1028 {
1029   gint status;
1030
1031   if G_UNLIKELY ((status = pthread_setspecific (*g_private_get_impl (key), value)) != 0)
1032     g_thread_abort (status, "pthread_setspecific");
1033 }
1034
1035 /**
1036  * g_private_replace:
1037  * @key: a #GPrivate
1038  * @value: the new value
1039  *
1040  * Sets the thread local variable @key to have the value @value in the
1041  * current thread.
1042  *
1043  * This function differs from g_private_set() in the following way: if
1044  * the previous value was non-%NULL then the #GDestroyNotify handler for
1045  * @key is run on it.
1046  *
1047  * Since: 2.32
1048  **/
1049 void
1050 g_private_replace (GPrivate *key,
1051                    gpointer  value)
1052 {
1053   pthread_key_t *impl = g_private_get_impl (key);
1054   gpointer old;
1055   gint status;
1056
1057   old = pthread_getspecific (*impl);
1058   if (old && key->notify)
1059     key->notify (old);
1060
1061   if G_UNLIKELY ((status = pthread_setspecific (*impl, value)) != 0)
1062     g_thread_abort (status, "pthread_setspecific");
1063 }
1064
1065 /* {{{1 GThread */
1066
1067 #define posix_check_err(err, name) G_STMT_START{                        \
1068   int error = (err);                                                    \
1069   if (error)                                                            \
1070     g_error ("file %s: line %d (%s): error '%s' during '%s'",           \
1071            __FILE__, __LINE__, G_STRFUNC,                               \
1072            g_strerror (error), name);                                   \
1073   }G_STMT_END
1074
1075 #define posix_check_cmd(cmd) posix_check_err (cmd, #cmd)
1076
1077 typedef struct
1078 {
1079   GRealThread thread;
1080
1081   pthread_t system_thread;
1082   gboolean  joined;
1083   GMutex    lock;
1084 } GThreadPosix;
1085
1086 void
1087 g_system_thread_free (GRealThread *thread)
1088 {
1089   GThreadPosix *pt = (GThreadPosix *) thread;
1090
1091   if (!pt->joined)
1092     pthread_detach (pt->system_thread);
1093
1094   g_mutex_clear (&pt->lock);
1095
1096   g_slice_free (GThreadPosix, pt);
1097 }
1098
1099 GRealThread *
1100 g_system_thread_new (GThreadFunc   thread_func,
1101                      gulong        stack_size,
1102                      GError      **error)
1103 {
1104   GThreadPosix *thread;
1105   pthread_attr_t attr;
1106   gint ret;
1107
1108   thread = g_slice_new0 (GThreadPosix);
1109
1110   posix_check_cmd (pthread_attr_init (&attr));
1111
1112 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1113   if (stack_size)
1114     {
1115 #ifdef _SC_THREAD_STACK_MIN
1116       stack_size = MAX (sysconf (_SC_THREAD_STACK_MIN), stack_size);
1117 #endif /* _SC_THREAD_STACK_MIN */
1118       /* No error check here, because some systems can't do it and
1119        * we simply don't want threads to fail because of that. */
1120       pthread_attr_setstacksize (&attr, stack_size);
1121     }
1122 #endif /* HAVE_PTHREAD_ATTR_SETSTACKSIZE */
1123
1124   ret = pthread_create (&thread->system_thread, &attr, (void* (*)(void*))thread_func, thread);
1125
1126   posix_check_cmd (pthread_attr_destroy (&attr));
1127
1128   if (ret == EAGAIN)
1129     {
1130       g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN, 
1131                    "Error creating thread: %s", g_strerror (ret));
1132       g_slice_free (GThreadPosix, thread);
1133       return NULL;
1134     }
1135
1136   posix_check_err (ret, "pthread_create");
1137
1138   g_mutex_init (&thread->lock);
1139
1140   return (GRealThread *) thread;
1141 }
1142
1143 /**
1144  * g_thread_yield:
1145  *
1146  * Causes the calling thread to voluntarily relinquish the CPU, so
1147  * that other threads can run.
1148  *
1149  * This function is often used as a method to make busy wait less evil.
1150  */
1151 void
1152 g_thread_yield (void)
1153 {
1154   sched_yield ();
1155 }
1156
1157 void
1158 g_system_thread_wait (GRealThread *thread)
1159 {
1160   GThreadPosix *pt = (GThreadPosix *) thread;
1161
1162   g_mutex_lock (&pt->lock);
1163
1164   if (!pt->joined)
1165     {
1166       posix_check_cmd (pthread_join (pt->system_thread, NULL));
1167       pt->joined = TRUE;
1168     }
1169
1170   g_mutex_unlock (&pt->lock);
1171 }
1172
1173 void
1174 g_system_thread_exit (void)
1175 {
1176   pthread_exit (NULL);
1177 }
1178
1179 void
1180 g_system_thread_set_name (const gchar *name)
1181 {
1182 #ifdef HAVE_SYS_PRCTL_H
1183 #ifdef PR_SET_NAME
1184   prctl (PR_SET_NAME, name, 0, 0, 0, 0);
1185 #endif
1186 #endif
1187 }
1188
1189 /* {{{1 Epilogue */
1190 /* vim:set foldmethod=marker: */