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