Rework GPrivate
[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 #include "gthreadprivate.h"
46
47 #include <pthread.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <errno.h>
51 #include <stdio.h>
52
53 static void
54 g_thread_abort (gint         status,
55                 const gchar *function)
56 {
57   fprintf (stderr, "GLib (gthread-posix.c): Unexpected error from C library during '%s': %s.  Aborting.\n",
58            strerror (status), function);
59   abort ();
60 }
61
62 /* {{{1 GMutex */
63 void
64 g_mutex_init (GMutex *mutex)
65 {
66   gint status;
67
68   if G_UNLIKELY ((status = pthread_mutex_init (&mutex->impl, NULL)) != 0)
69     g_thread_abort (status, "pthread_mutex_init");
70 }
71
72 void
73 g_mutex_clear (GMutex *mutex)
74 {
75   gint status;
76
77   if G_UNLIKELY ((status = pthread_mutex_destroy (&mutex->impl)) != 0)
78     g_thread_abort (status, "pthread_mutex_destroy");
79 }
80
81 void
82 g_mutex_lock (GMutex *mutex)
83 {
84   gint status;
85
86   if G_UNLIKELY ((status = pthread_mutex_lock (&mutex->impl)) != 0)
87     g_thread_abort (status, "pthread_mutex_lock");
88 }
89
90 void
91 g_mutex_unlock (GMutex *mutex)
92 {
93   gint status;
94
95   if G_UNLIKELY ((status = pthread_mutex_unlock (&mutex->impl)) != 0)
96     g_thread_abort (status, "pthread_mutex_lock");
97 }
98
99 gboolean
100 g_mutex_trylock (GMutex *mutex)
101 {
102   gint status;
103
104   if G_LIKELY ((status = pthread_mutex_trylock (&mutex->impl)) == 0)
105     return TRUE;
106
107   if G_UNLIKELY (status != EBUSY)
108     g_thread_abort (status, "pthread_mutex_trylock");
109
110   return FALSE;
111 }
112
113 /* {{{1 GCond */
114
115 void
116 g_cond_init (GCond *cond)
117 {
118   gint status;
119
120   if G_UNLIKELY ((status = pthread_cond_init (&cond->impl, NULL)) != 0)
121     g_thread_abort (status, "pthread_cond_init");
122 }
123
124 void
125 g_cond_clear (GCond *cond)
126 {
127   gint status;
128
129   if G_UNLIKELY ((status = pthread_cond_destroy (&cond->impl)) != 0)
130     g_thread_abort (status, "pthread_cond_destroy");
131 }
132
133 void
134 g_cond_wait (GCond  *cond,
135              GMutex *mutex)
136 {
137   gint status;
138
139   if G_UNLIKELY ((status = pthread_cond_wait (&cond->impl, &mutex->impl)) != 0)
140     g_thread_abort (status, "pthread_cond_wait");
141 }
142
143 void
144 g_cond_signal (GCond *cond)
145 {
146   gint status;
147
148   if G_UNLIKELY ((status = pthread_cond_signal (&cond->impl)) != 0)
149     g_thread_abort (status, "pthread_cond_signal");
150 }
151
152 void
153 g_cond_broadcast (GCond *cond)
154 {
155   gint status;
156
157   if G_UNLIKELY ((status = pthread_cond_broadcast (&cond->impl)) != 0)
158     g_thread_abort (status, "pthread_cond_broadcast");
159 }
160
161 gboolean
162 g_cond_timed_wait (GCond    *cond,
163                    GMutex   *mutex,
164                    GTimeVal *abs_time)
165 {
166   struct timespec end_time;
167   gint status;
168
169   if (abs_time == NULL)
170     {
171       g_cond_wait (cond, mutex);
172       return TRUE;
173     }
174
175   end_time.tv_sec = abs_time->tv_sec;
176   end_time.tv_nsec = abs_time->tv_usec * 1000;
177
178   if ((status = pthread_cond_timedwait (&cond->impl, &mutex->impl, &end_time)) == 0)
179     return TRUE;
180
181   if G_UNLIKELY (status != ETIMEDOUT)
182     g_thread_abort (status, "pthread_cond_timedwait");
183
184   return FALSE;
185 }
186
187 gboolean
188 g_cond_timedwait (GCond  *cond,
189                   GMutex *mutex,
190                   gint64  abs_time)
191 {
192   struct timespec end_time;
193   gint status;
194
195   end_time.tv_sec = abs_time / 1000000;
196   end_time.tv_nsec = (abs_time % 1000000) * 1000;
197
198   if ((status = pthread_cond_timedwait (&cond->impl, &mutex->impl, &end_time)) == 0)
199     return TRUE;
200
201   if G_UNLIKELY (status != ETIMEDOUT)
202     g_thread_abort (status, "pthread_cond_timedwait");
203
204   return FALSE;
205 }
206
207 /* {{{1 GPrivate */
208
209 GPrivate *
210 (g_private_new) (GDestroyNotify notify)
211 {
212   GPrivate *key;
213
214   key = malloc (sizeof (GPrivate));
215   if G_UNLIKELY (key == NULL)
216     g_thread_abort (errno, "malloc");
217   g_private_init (key, notify);
218
219   return key;
220 }
221
222 void
223 g_private_init (GPrivate       *key,
224                 GDestroyNotify  notify)
225 {
226   pthread_key_create (&key->key, notify);
227 }
228
229 gpointer
230 (g_private_get) (GPrivate *key)
231 {
232   /* quote POSIX: No errors are returned from pthread_getspecific(). */
233   return pthread_getspecific (key->key);
234 }
235
236 void
237 (g_private_set) (GPrivate *key,
238                  gpointer  value)
239 {
240   gint status;
241
242   if G_UNLIKELY ((status = pthread_setspecific (key->key, value)) != 0)
243     g_thread_abort (status, "pthread_setspecific");
244 }
245
246 /* {{{1 GThread */
247
248 #include "glib.h"
249 #include "gthreadprivate.h"
250
251 #include <pthread.h>
252 #include <errno.h>
253 #include <stdlib.h>
254 #ifdef HAVE_SYS_TIME_H
255 # include <sys/time.h>
256 #endif
257 #ifdef HAVE_UNISTD_H
258 # include <unistd.h>
259 #endif
260
261 #ifdef HAVE_SCHED_H
262 #include <sched.h>
263 #endif
264
265 #define posix_check_err(err, name) G_STMT_START{                        \
266   int error = (err);                                                    \
267   if (error)                                                            \
268     g_error ("file %s: line %d (%s): error '%s' during '%s'",           \
269            __FILE__, __LINE__, G_STRFUNC,                               \
270            g_strerror (error), name);                                   \
271   }G_STMT_END
272
273 #define posix_check_cmd(cmd) posix_check_err (cmd, #cmd)
274
275 #ifdef G_ENABLE_DEBUG
276 static gboolean posix_check_cmd_prio_warned = FALSE;
277 # define posix_check_cmd_prio(cmd) G_STMT_START{                        \
278     int err = (cmd);                                                    \
279     if (err == EPERM)                                                   \
280       {                                                                 \
281         if (!posix_check_cmd_prio_warned)                               \
282           {                                                             \
283             posix_check_cmd_prio_warned = TRUE;                         \
284             g_warning ("Priorities can only be changed "                \
285                         "(resp. increased) by root.");                  \
286           }                                                             \
287       }                                                                 \
288     else                                                                \
289       posix_check_err (err, #cmd);                                      \
290      }G_STMT_END
291 #else /* G_ENABLE_DEBUG */
292 # define posix_check_cmd_prio(cmd) G_STMT_START{                        \
293     int err = (cmd);                                                    \
294     if (err != EPERM)                                                   \
295       posix_check_err (err, #cmd);                                      \
296      }G_STMT_END
297 #endif /* G_ENABLE_DEBUG */
298
299 #if defined (POSIX_MIN_PRIORITY) && defined (POSIX_MAX_PRIORITY)
300 # define HAVE_PRIORITIES 1
301 static gint priority_normal_value;
302 # ifdef __FreeBSD__
303    /* FreeBSD threads use different priority values from the POSIX_
304     * defines so we just set them here. The corresponding macros
305     * PTHREAD_MIN_PRIORITY and PTHREAD_MAX_PRIORITY are implied to be
306     * exported by the docs, but they aren't.
307     */
308 #  define PRIORITY_LOW_VALUE      0
309 #  define PRIORITY_URGENT_VALUE   31
310 # else /* !__FreeBSD__ */
311 #  define PRIORITY_LOW_VALUE      POSIX_MIN_PRIORITY
312 #  define PRIORITY_URGENT_VALUE   POSIX_MAX_PRIORITY
313 # endif /* !__FreeBSD__ */
314 # define PRIORITY_NORMAL_VALUE    priority_normal_value
315
316 # define PRIORITY_HIGH_VALUE \
317     ((PRIORITY_NORMAL_VALUE + PRIORITY_URGENT_VALUE * 2) / 3)
318
319 static gint
320 g_thread_priority_map (GThreadPriority priority)
321 {
322   switch (priority)
323     {
324     case G_THREAD_PRIORITY_LOW:
325       return PRIORITY_LOW_VALUE;
326
327     case G_THREAD_PRIORITY_NORMAL:
328       return PRIORITY_NORMAL_VALUE;
329
330     case G_THREAD_PRIORITY_HIGH:
331       return PRIORITY_HIGH_VALUE;
332
333     case G_THREAD_PRIORITY_URGENT:
334       return PRIORITY_URGENT_VALUE;
335
336     default:
337       g_assert_not_reached ();
338     }
339 }
340
341 #endif /* POSIX_MIN_PRIORITY && POSIX_MAX_PRIORITY */
342
343 static gulong g_thread_min_stack_size = 0;
344
345 #define G_MUTEX_SIZE (sizeof (pthread_mutex_t))
346
347 void
348 _g_thread_impl_init(void)
349 {
350 #ifdef _SC_THREAD_STACK_MIN
351   g_thread_min_stack_size = MAX (sysconf (_SC_THREAD_STACK_MIN), 0);
352 #endif /* _SC_THREAD_STACK_MIN */
353 #ifdef HAVE_PRIORITIES
354   {
355     struct sched_param sched;
356     int policy;
357     posix_check_cmd (pthread_getschedparam (pthread_self(), &policy, &sched));
358     priority_normal_value = sched.sched_priority;
359   }
360 #endif /* HAVE_PRIORITIES */
361 }
362
363 static void
364 g_thread_create_posix_impl (GThreadFunc thread_func,
365                             gpointer arg,
366                             gulong stack_size,
367                             gboolean joinable,
368                             gboolean bound,
369                             GThreadPriority priority,
370                             gpointer thread,
371                             GError **error)
372 {
373   pthread_attr_t attr;
374   gint ret;
375
376   g_return_if_fail (thread_func);
377   g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
378   g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);
379
380   posix_check_cmd (pthread_attr_init (&attr));
381
382 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
383   if (stack_size)
384     {
385       stack_size = MAX (g_thread_min_stack_size, stack_size);
386       /* No error check here, because some systems can't do it and
387        * we simply don't want threads to fail because of that. */
388       pthread_attr_setstacksize (&attr, stack_size);
389     }
390 #endif /* HAVE_PTHREAD_ATTR_SETSTACKSIZE */
391
392 #ifdef PTHREAD_SCOPE_SYSTEM
393   if (bound)
394     /* No error check here, because some systems can't do it and we
395      * simply don't want threads to fail because of that. */
396     pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM);
397 #endif /* PTHREAD_SCOPE_SYSTEM */
398
399   posix_check_cmd (pthread_attr_setdetachstate (&attr,
400           joinable ? PTHREAD_CREATE_JOINABLE : PTHREAD_CREATE_DETACHED));
401
402 #ifdef HAVE_PRIORITIES
403   {
404     struct sched_param sched;
405     posix_check_cmd (pthread_attr_getschedparam (&attr, &sched));
406     sched.sched_priority = g_thread_priority_map (priority);
407     posix_check_cmd_prio (pthread_attr_setschedparam (&attr, &sched));
408   }
409 #endif /* HAVE_PRIORITIES */
410   ret = pthread_create (thread, &attr, (void* (*)(void*))thread_func, arg);
411
412   posix_check_cmd (pthread_attr_destroy (&attr));
413
414   if (ret == EAGAIN)
415     {
416       g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN, 
417                    "Error creating thread: %s", g_strerror (ret));
418       return;
419     }
420
421   posix_check_err (ret, "pthread_create");
422 }
423
424 static void
425 g_thread_yield_posix_impl (void)
426 {
427   POSIX_YIELD_FUNC;
428 }
429
430 static void
431 g_thread_join_posix_impl (gpointer thread)
432 {
433   gpointer ignore;
434   posix_check_cmd (pthread_join (*(pthread_t*)thread, &ignore));
435 }
436
437 static void
438 g_thread_exit_posix_impl (void)
439 {
440   pthread_exit (NULL);
441 }
442
443 static void
444 g_thread_set_priority_posix_impl (gpointer thread, GThreadPriority priority)
445 {
446   g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
447   g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);
448 #ifdef HAVE_PRIORITIES
449   {
450     struct sched_param sched;
451     int policy;
452     posix_check_cmd (pthread_getschedparam (*(pthread_t*)thread, &policy,
453                                             &sched));
454     sched.sched_priority = g_thread_priority_map (priority);
455     posix_check_cmd_prio (pthread_setschedparam (*(pthread_t*)thread, policy,
456                                                  &sched));
457   }
458 #endif /* HAVE_PRIORITIES */
459 }
460
461 static void
462 g_thread_self_posix_impl (gpointer thread)
463 {
464   *(pthread_t*)thread = pthread_self();
465 }
466
467 static gboolean
468 g_thread_equal_posix_impl (gpointer thread1, gpointer thread2)
469 {
470   return (pthread_equal (*(pthread_t*)thread1, *(pthread_t*)thread2) != 0);
471 }
472
473 /* {{{1 Epilogue */
474 GThreadFunctions g_thread_functions_for_glib_use =
475 {
476   g_mutex_new,
477   g_mutex_lock,
478   g_mutex_trylock,
479   g_mutex_unlock,
480   g_mutex_free,
481   g_cond_new,
482   g_cond_signal,
483   g_cond_broadcast,
484   g_cond_wait,
485   g_cond_timed_wait,
486   g_cond_free,
487   g_private_new,
488   g_private_get,
489   g_private_set,
490   g_thread_create_posix_impl,
491   g_thread_yield_posix_impl,
492   g_thread_join_posix_impl,
493   g_thread_exit_posix_impl,
494   g_thread_set_priority_posix_impl,
495   g_thread_self_posix_impl,
496   g_thread_equal_posix_impl
497 };
498
499 /* vim:set foldmethod=marker: */