96abcf80e049895f771db3b6acb757dc16b2b9f5
[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 /*
31  * MT safe
32  */
33
34 #include "config.h"
35
36 #include "glib.h"
37 #include "gthreadprivate.h"
38
39 #include <pthread.h>
40 #include <errno.h>
41 #include <stdlib.h>
42 #ifdef HAVE_SYS_TIME_H
43 # include <sys/time.h>
44 #endif
45 #ifdef HAVE_UNISTD_H
46 # include <unistd.h>
47 #endif
48
49 #ifdef HAVE_SCHED_H
50 #include <sched.h>
51 #endif
52
53 #define posix_check_err(err, name) G_STMT_START{                        \
54   int error = (err);                                                    \
55   if (error)                                                            \
56     g_error ("file %s: line %d (%s): error '%s' during '%s'",           \
57            __FILE__, __LINE__, G_STRFUNC,                               \
58            g_strerror (error), name);                                   \
59   }G_STMT_END
60
61 #define posix_check_cmd(cmd) posix_check_err (cmd, #cmd)
62
63 #ifdef G_ENABLE_DEBUG
64 static gboolean posix_check_cmd_prio_warned = FALSE;
65 # define posix_check_cmd_prio(cmd) G_STMT_START{                        \
66     int err = (cmd);                                                    \
67     if (err == EPERM)                                                   \
68       {                                                                 \
69         if (!posix_check_cmd_prio_warned)                               \
70           {                                                             \
71             posix_check_cmd_prio_warned = TRUE;                         \
72             g_warning ("Priorities can only be changed "                \
73                         "(resp. increased) by root.");                  \
74           }                                                             \
75       }                                                                 \
76     else                                                                \
77       posix_check_err (err, #cmd);                                      \
78      }G_STMT_END
79 #else /* G_ENABLE_DEBUG */
80 # define posix_check_cmd_prio(cmd) G_STMT_START{                        \
81     int err = (cmd);                                                    \
82     if (err != EPERM)                                                   \
83       posix_check_err (err, #cmd);                                      \
84      }G_STMT_END
85 #endif /* G_ENABLE_DEBUG */
86
87 #if defined (POSIX_MIN_PRIORITY) && defined (POSIX_MAX_PRIORITY)
88 # define HAVE_PRIORITIES 1
89 static gint priority_normal_value;
90 # ifdef __FreeBSD__
91    /* FreeBSD threads use different priority values from the POSIX_
92     * defines so we just set them here. The corresponding macros
93     * PTHREAD_MIN_PRIORITY and PTHREAD_MAX_PRIORITY are implied to be
94     * exported by the docs, but they aren't.
95     */
96 #  define PRIORITY_LOW_VALUE      0
97 #  define PRIORITY_URGENT_VALUE   31
98 # else /* !__FreeBSD__ */
99 #  define PRIORITY_LOW_VALUE      POSIX_MIN_PRIORITY
100 #  define PRIORITY_URGENT_VALUE   POSIX_MAX_PRIORITY
101 # endif /* !__FreeBSD__ */
102 # define PRIORITY_NORMAL_VALUE    priority_normal_value
103
104 # define PRIORITY_HIGH_VALUE \
105     ((PRIORITY_NORMAL_VALUE + PRIORITY_URGENT_VALUE * 2) / 3)
106
107 static gint
108 g_thread_priority_map (GThreadPriority priority)
109 {
110   switch (priority)
111     {
112     case G_THREAD_PRIORITY_LOW:
113       return PRIORITY_LOW_VALUE;
114
115     case G_THREAD_PRIORITY_NORMAL:
116       return PRIORITY_NORMAL_VALUE;
117
118     case G_THREAD_PRIORITY_HIGH:
119       return PRIORITY_HIGH_VALUE;
120
121     case G_THREAD_PRIORITY_URGENT:
122       return PRIORITY_URGENT_VALUE;
123
124     default:
125       g_assert_not_reached ();
126     }
127 }
128
129 #endif /* POSIX_MIN_PRIORITY && POSIX_MAX_PRIORITY */
130
131 static gulong g_thread_min_stack_size = 0;
132
133 #define G_MUTEX_SIZE (sizeof (pthread_mutex_t))
134
135 void
136 _g_thread_impl_init(void)
137 {
138 #ifdef _SC_THREAD_STACK_MIN
139   g_thread_min_stack_size = MAX (sysconf (_SC_THREAD_STACK_MIN), 0);
140 #endif /* _SC_THREAD_STACK_MIN */
141 #ifdef HAVE_PRIORITIES
142   {
143     struct sched_param sched;
144     int policy;
145     posix_check_cmd (pthread_getschedparam (pthread_self(), &policy, &sched));
146     priority_normal_value = sched.sched_priority;
147   }
148 #endif /* HAVE_PRIORITIES */
149 }
150
151 static GMutex *
152 g_mutex_new_posix_impl (void)
153 {
154   GMutex *result = (GMutex *) g_new (pthread_mutex_t, 1);
155   posix_check_cmd (pthread_mutex_init ((pthread_mutex_t *) result, NULL));
156   return result;
157 }
158
159 static void
160 g_mutex_free_posix_impl (GMutex * mutex)
161 {
162   posix_check_cmd (pthread_mutex_destroy ((pthread_mutex_t *) mutex));
163   g_free (mutex);
164 }
165
166 /* NOTE: the functions g_mutex_lock and g_mutex_unlock may not use
167    functions from gmem.c and gmessages.c; */
168
169 /* pthread_mutex_lock, pthread_mutex_unlock can be taken directly, as
170    signature and semantic are right, but without error check then!!!!,
171    we might want to change this therefore. */
172
173 static gboolean
174 g_mutex_trylock_posix_impl (GMutex * mutex)
175 {
176   int result;
177
178   result = pthread_mutex_trylock ((pthread_mutex_t *) mutex);
179
180   if (result == EBUSY)
181     return FALSE;
182
183   posix_check_err (result, "pthread_mutex_trylock");
184   return TRUE;
185 }
186
187 static GCond *
188 g_cond_new_posix_impl (void)
189 {
190   GCond *result = (GCond *) g_new (pthread_cond_t, 1);
191   posix_check_cmd (pthread_cond_init ((pthread_cond_t *) result, NULL));
192   return result;
193 }
194
195 /* pthread_cond_signal, pthread_cond_broadcast and pthread_cond_wait
196    can be taken directly, as signature and semantic are right, but
197    without error check then!!!!, we might want to change this
198    therefore. */
199
200 #define G_NSEC_PER_SEC 1000000000
201
202 static gboolean
203 g_cond_timed_wait_posix_impl (GCond * cond,
204                               GMutex * entered_mutex,
205                               GTimeVal * abs_time)
206 {
207   int result;
208   struct timespec end_time;
209   gboolean timed_out;
210
211   g_return_val_if_fail (cond != NULL, FALSE);
212   g_return_val_if_fail (entered_mutex != NULL, FALSE);
213
214   if (!abs_time)
215     {
216       result = pthread_cond_wait ((pthread_cond_t *)cond,
217                                   (pthread_mutex_t *) entered_mutex);
218       timed_out = FALSE;
219     }
220   else
221     {
222       end_time.tv_sec = abs_time->tv_sec;
223       end_time.tv_nsec = abs_time->tv_usec * (G_NSEC_PER_SEC / G_USEC_PER_SEC);
224
225       g_return_val_if_fail (end_time.tv_nsec < G_NSEC_PER_SEC, TRUE);
226
227       result = pthread_cond_timedwait ((pthread_cond_t *) cond,
228                                        (pthread_mutex_t *) entered_mutex,
229                                        &end_time);
230       timed_out = (result == ETIMEDOUT);
231     }
232
233   if (!timed_out)
234     posix_check_err (result, "pthread_cond_timedwait");
235
236   return !timed_out;
237 }
238
239 static void
240 g_cond_free_posix_impl (GCond * cond)
241 {
242   posix_check_cmd (pthread_cond_destroy ((pthread_cond_t *) cond));
243   g_free (cond);
244 }
245
246 static GPrivate *
247 g_private_new_posix_impl (GDestroyNotify destructor)
248 {
249   GPrivate *result = (GPrivate *) g_new (pthread_key_t, 1);
250   posix_check_cmd (pthread_key_create ((pthread_key_t *) result, destructor));
251   return result;
252 }
253
254 /* NOTE: the functions g_private_get and g_private_set may not use
255    functions from gmem.c and gmessages.c */
256
257 static void
258 g_private_set_posix_impl (GPrivate * private_key, gpointer value)
259 {
260   if (!private_key)
261     return;
262   pthread_setspecific (*(pthread_key_t *) private_key, value);
263 }
264
265 static gpointer
266 g_private_get_posix_impl (GPrivate * private_key)
267 {
268   if (!private_key)
269     return NULL;
270
271   return pthread_getspecific (*(pthread_key_t *) private_key);
272 }
273
274 static void
275 g_thread_create_posix_impl (GThreadFunc thread_func,
276                             gpointer arg,
277                             gulong stack_size,
278                             gboolean joinable,
279                             gboolean bound,
280                             GThreadPriority priority,
281                             gpointer thread,
282                             GError **error)
283 {
284   pthread_attr_t attr;
285   gint ret;
286
287   g_return_if_fail (thread_func);
288   g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
289   g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);
290
291   posix_check_cmd (pthread_attr_init (&attr));
292
293 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
294   if (stack_size)
295     {
296       stack_size = MAX (g_thread_min_stack_size, stack_size);
297       /* No error check here, because some systems can't do it and
298        * we simply don't want threads to fail because of that. */
299       pthread_attr_setstacksize (&attr, stack_size);
300     }
301 #endif /* HAVE_PTHREAD_ATTR_SETSTACKSIZE */
302
303 #ifdef PTHREAD_SCOPE_SYSTEM
304   if (bound)
305     /* No error check here, because some systems can't do it and we
306      * simply don't want threads to fail because of that. */
307     pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM);
308 #endif /* PTHREAD_SCOPE_SYSTEM */
309
310   posix_check_cmd (pthread_attr_setdetachstate (&attr,
311           joinable ? PTHREAD_CREATE_JOINABLE : PTHREAD_CREATE_DETACHED));
312
313 #ifdef HAVE_PRIORITIES
314   {
315     struct sched_param sched;
316     posix_check_cmd (pthread_attr_getschedparam (&attr, &sched));
317     sched.sched_priority = g_thread_priority_map (priority);
318     posix_check_cmd_prio (pthread_attr_setschedparam (&attr, &sched));
319   }
320 #endif /* HAVE_PRIORITIES */
321   ret = pthread_create (thread, &attr, (void* (*)(void*))thread_func, arg);
322
323   posix_check_cmd (pthread_attr_destroy (&attr));
324
325   if (ret == EAGAIN)
326     {
327       g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN, 
328                    "Error creating thread: %s", g_strerror (ret));
329       return;
330     }
331
332   posix_check_err (ret, "pthread_create");
333 }
334
335 static void
336 g_thread_yield_posix_impl (void)
337 {
338   POSIX_YIELD_FUNC;
339 }
340
341 static void
342 g_thread_join_posix_impl (gpointer thread)
343 {
344   gpointer ignore;
345   posix_check_cmd (pthread_join (*(pthread_t*)thread, &ignore));
346 }
347
348 static void
349 g_thread_exit_posix_impl (void)
350 {
351   pthread_exit (NULL);
352 }
353
354 static void
355 g_thread_set_priority_posix_impl (gpointer thread, GThreadPriority priority)
356 {
357   g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
358   g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);
359 #ifdef HAVE_PRIORITIES
360   {
361     struct sched_param sched;
362     int policy;
363     posix_check_cmd (pthread_getschedparam (*(pthread_t*)thread, &policy,
364                                             &sched));
365     sched.sched_priority = g_thread_priority_map (priority);
366     posix_check_cmd_prio (pthread_setschedparam (*(pthread_t*)thread, policy,
367                                                  &sched));
368   }
369 #endif /* HAVE_PRIORITIES */
370 }
371
372 static void
373 g_thread_self_posix_impl (gpointer thread)
374 {
375   *(pthread_t*)thread = pthread_self();
376 }
377
378 static gboolean
379 g_thread_equal_posix_impl (gpointer thread1, gpointer thread2)
380 {
381   return (pthread_equal (*(pthread_t*)thread1, *(pthread_t*)thread2) != 0);
382 }
383
384 GThreadFunctions g_thread_functions_for_glib_use =
385 {
386   g_mutex_new_posix_impl,
387   (void (*)(GMutex *)) pthread_mutex_lock,
388   g_mutex_trylock_posix_impl,
389   (void (*)(GMutex *)) pthread_mutex_unlock,
390   g_mutex_free_posix_impl,
391   g_cond_new_posix_impl,
392   (void (*)(GCond *)) pthread_cond_signal,
393   (void (*)(GCond *)) pthread_cond_broadcast,
394   (void (*)(GCond *, GMutex *)) pthread_cond_wait,
395   g_cond_timed_wait_posix_impl,
396   g_cond_free_posix_impl,
397   g_private_new_posix_impl,
398   g_private_get_posix_impl,
399   g_private_set_posix_impl,
400   g_thread_create_posix_impl,
401   g_thread_yield_posix_impl,
402   g_thread_join_posix_impl,
403   g_thread_exit_posix_impl,
404   g_thread_set_priority_posix_impl,
405   g_thread_self_posix_impl,
406   g_thread_equal_posix_impl
407 };