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