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