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