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