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