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