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