gthread-posix.c 13.2 KB
Newer Older
1 2 3 4 5 6 7
/* GLIB - Library of useful routines for C programming
 * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
 *
 * gthread.c: posix thread system implementation
 * Copyright 1998 Sebastian Wilhelmi; University of Karlsruhe
 *
 * This library is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9 10 11 12 13 14
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * 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 19 20 21 22
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

23
/*
24
 * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
25 26
 * file for a list of people on the GLib Team.  See the ChangeLog
 * files for a list of changes.  These files are distributed with
27
 * GLib at ftp://ftp.gtk.org/pub/gtk/.
28 29
 */

30
/*
31 32 33
 * MT safe
 */

34
#include "config.h"
35

36 37 38
#include <pthread.h>
#include <errno.h>
#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 47 48
#ifdef HAVE_SCHED_H
#include <sched.h>
#endif
49

50 51 52
#define posix_check_err(err, name) G_STMT_START{			\
  int error = (err); 							\
  if (error)	 		 		 			\
53
    g_error ("file %s: line %d (%s): error '%s' during '%s'",		\
54
           __FILE__, __LINE__, G_GNUC_PRETTY_FUNCTION,			\
55 56 57 58 59 60 61 62 63 64 65 66 67 68
           g_strerror (error), name);					\
  }G_STMT_END

#define posix_check_cmd(cmd) posix_check_err (posix_error (cmd), #cmd)

#ifdef G_ENABLE_DEBUG
static gboolean posix_check_cmd_prio_warned = FALSE;
# define posix_check_cmd_prio(cmd) G_STMT_START{			\
    int err = posix_error (cmd);					\
    if (err == EPERM)		 		 			\
      { 	 			 				\
        if (!posix_check_cmd_prio_warned) 		 		\
          { 	 				 			\
            posix_check_cmd_prio_warned = TRUE;		 		\
69 70
            g_warning ("Priorities can only be changed " 		\
                        "(resp. increased) by root."); 			\
71 72 73 74 75 76 77 78 79 80 81 82
          }			 					\
      }			 						\
    else  		 						\
      posix_check_err (err, #cmd);					\
     }G_STMT_END
#else /* G_ENABLE_DEBUG */
# define posix_check_cmd_prio(cmd) G_STMT_START{			\
    int err = posix_error (cmd);					\
    if (err != EPERM)		 		 			\
      posix_check_err (err, #cmd);					\
     }G_STMT_END
#endif /* G_ENABLE_DEBUG */
83

84
#if defined(G_THREADS_IMPL_POSIX)
85
# define posix_error(what) (what)
86 87
# define mutexattr_default NULL
# define condattr_default NULL
88
#elif defined(G_THREADS_IMPL_DCE)
89
# define posix_error(what) ((what) == -1 ? errno : 0)
90 91 92
# define pthread_key_create(a, b) pthread_keycreate (a, b)
# define pthread_attr_init(a) pthread_attr_create (a)
# define pthread_attr_destroy(a) pthread_attr_delete (a)
93
# define pthread_create(a, b, c, d) pthread_create (a, *b, c, d)
94 95
# define mutexattr_default (pthread_mutexattr_default)
# 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 104 105 106 107 108 109 110 111
# ifdef __FreeBSD__
   /* FreeBSD threads use different priority values from the POSIX_
    * defines so we just set them here. The corresponding macros
    * PTHREAD_MIN_PRIORITY and PTHREAD_MAX_PRIORITY are implied to be
    * exported by the docs, but they aren't.
    */
#  define PRIORITY_LOW_VALUE      0
#  define PRIORITY_URGENT_VALUE   31
# else /* !__FreeBSD__ */
112 113
#  define PRIORITY_LOW_VALUE      POSIX_MIN_PRIORITY
#  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 121
#define G_MUTEX_SIZE (sizeof (pthread_mutex_t))

122 123 124 125 126 127
static gint posix_clock = 0;
#if defined(HAVE_CLOCK_GETTIME) && defined(HAVE_MONOTONIC_CLOCK) 
#define USE_CLOCK_GETTIME 1
#endif

#if defined(_SC_THREAD_STACK_MIN) || defined (HAVE_PRIORITIES) || defined (USE_CLOCK_GETTIME)
128
#define HAVE_G_THREAD_IMPL_INIT
129
static void
130
g_thread_impl_init(void)
131
{
132
#ifdef _SC_THREAD_STACK_MIN
133
  g_thread_min_stack_size = MAX (sysconf (_SC_THREAD_STACK_MIN), 0);
134
#endif /* _SC_THREAD_STACK_MIN */
135 136 137 138 139 140 141 142 143
#ifdef HAVE_PRIORITIES
# ifdef G_THREADS_IMPL_POSIX
  {
    struct sched_param sched;
    int policy;
    posix_check_cmd (pthread_getschedparam (pthread_self(), &policy, &sched));
    priority_normal_value = sched.sched_priority;
  }
# else /* G_THREADS_IMPL_DCE */
144 145
  posix_check_cmd (priority_normal_value =
		   pthread_getprio (*(pthread_t*)thread,
146 147 148 149
				    g_thread_priority_map [priority]));
# endif
#endif /* HAVE_PRIORITIES */

150 151 152 153
 if (sysconf (_SC_MONOTONIC_CLOCK) >= 0)
   posix_clock = CLOCK_MONOTONIC;
 else
   posix_clock = CLOCK_REALTIME;
154 155
}
#endif /* _SC_THREAD_STACK_MIN || HAVE_PRIORITIES */
156

157 158 159 160
static GMutex *
g_mutex_new_posix_impl (void)
{
  GMutex *result = (GMutex *) g_new (pthread_mutex_t, 1);
161
  posix_check_cmd (pthread_mutex_init ((pthread_mutex_t *) result,
162
				       mutexattr_default));
163 164 165 166 167 168
  return result;
}

static void
g_mutex_free_posix_impl (GMutex * mutex)
{
169
  posix_check_cmd (pthread_mutex_destroy ((pthread_mutex_t *) mutex));
170
  g_free (mutex);
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
}

/* NOTE: the functions g_mutex_lock and g_mutex_unlock may not use
   functions from gmem.c and gmessages.c; */

/* pthread_mutex_lock, pthread_mutex_unlock can be taken directly, as
   signature and semantic are right, but without error check then!!!!,
   we might want to change this therefore. */

static gboolean
g_mutex_trylock_posix_impl (GMutex * mutex)
{
  int result;

  result = pthread_mutex_trylock ((pthread_mutex_t *) mutex);
186 187 188

#ifdef G_THREADS_IMPL_POSIX
  if (result == EBUSY)
189
    return FALSE;
190 191 192 193
#else /* G_THREADS_IMPL_DCE */
  if (result == 0)
    return FALSE;
#endif
194

195
  posix_check_err (posix_error (result), "pthread_mutex_trylock");
196 197 198 199 200 201 202
  return TRUE;
}

static GCond *
g_cond_new_posix_impl (void)
{
  GCond *result = (GCond *) g_new (pthread_cond_t, 1);
203
  posix_check_cmd (pthread_cond_init ((pthread_cond_t *) result,
204
				      condattr_default));
205 206 207 208 209 210
  return result;
}

/* pthread_cond_signal, pthread_cond_broadcast and pthread_cond_wait
   can be taken directly, as signature and semantic are right, but
   without error check then!!!!, we might want to change this
211
   therefore. */
212

213
#define G_NSEC_PER_SEC 1000000000
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228

static gboolean
g_cond_timed_wait_posix_impl (GCond * cond,
			      GMutex * entered_mutex,
			      GTimeVal * abs_time)
{
  int result;
  struct timespec end_time;
  gboolean timed_out;

  g_return_val_if_fail (cond != NULL, FALSE);
  g_return_val_if_fail (entered_mutex != NULL, FALSE);

  if (!abs_time)
    {
229 230 231
      result = pthread_cond_wait ((pthread_cond_t *)cond,
                                  (pthread_mutex_t *) entered_mutex);
      timed_out = FALSE;
232
    }
233 234 235 236
  else
    {
      end_time.tv_sec = abs_time->tv_sec;
      end_time.tv_nsec = abs_time->tv_usec * (G_NSEC_PER_SEC / G_USEC_PER_SEC);
237

238
      g_return_val_if_fail (end_time.tv_nsec < G_NSEC_PER_SEC, TRUE);
239

240 241 242
      result = pthread_cond_timedwait ((pthread_cond_t *) cond,
                                       (pthread_mutex_t *) entered_mutex,
                                       &end_time);
243
#ifdef G_THREADS_IMPL_POSIX
244
      timed_out = (result == ETIMEDOUT);
245
#else /* G_THREADS_IMPL_DCE */
246
      timed_out = (result == -1) && (errno == EAGAIN);
247
#endif
248
    }
249

250
  if (!timed_out)
251
    posix_check_err (posix_error (result), "pthread_cond_timedwait");
252

253 254 255 256 257 258
  return !timed_out;
}

static void
g_cond_free_posix_impl (GCond * cond)
{
259
  posix_check_cmd (pthread_cond_destroy ((pthread_cond_t *) cond));
260 261 262 263 264 265 266
  g_free (cond);
}

static GPrivate *
g_private_new_posix_impl (GDestroyNotify destructor)
{
  GPrivate *result = (GPrivate *) g_new (pthread_key_t, 1);
267
  posix_check_cmd (pthread_key_create ((pthread_key_t *) result, destructor));
268 269 270 271 272 273 274
  return result;
}

/* NOTE: the functions g_private_get and g_private_set may not use
   functions from gmem.c and gmessages.c */

static void
Sebastian Wilhelmi's avatar
Sebastian Wilhelmi committed
275
g_private_set_posix_impl (GPrivate * private_key, gpointer value)
276
{
Sebastian Wilhelmi's avatar
Sebastian Wilhelmi committed
277
  if (!private_key)
278
    return;
Sebastian Wilhelmi's avatar
Sebastian Wilhelmi committed
279
  pthread_setspecific (*(pthread_key_t *) private_key, value);
280 281 282
}

static gpointer
Sebastian Wilhelmi's avatar
Sebastian Wilhelmi committed
283
g_private_get_posix_impl (GPrivate * private_key)
284
{
Sebastian Wilhelmi's avatar
Sebastian Wilhelmi committed
285
  if (!private_key)
286
    return NULL;
287
#ifdef G_THREADS_IMPL_POSIX
Sebastian Wilhelmi's avatar
Sebastian Wilhelmi committed
288
  return pthread_getspecific (*(pthread_key_t *) private_key);
289
#else /* G_THREADS_IMPL_DCE */
290 291
  {
    void* data;
292
    posix_check_cmd (pthread_getspecific (*(pthread_key_t *) private_key,
293
					  &data));
294 295
    return data;
  }
296 297 298
#endif
}

299
static void
300 301
g_thread_create_posix_impl (GThreadFunc thread_func,
			    gpointer arg,
302 303 304
			    gulong stack_size,
			    gboolean joinable,
			    gboolean bound,
305
			    GThreadPriority priority,
306 307
			    gpointer thread,
			    GError **error)
308
{
309
  pthread_attr_t attr;
310
  gint ret;
311

312
  g_return_if_fail (thread_func);
313 314
  g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
  g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);
315

316
  posix_check_cmd (pthread_attr_init (&attr));
317

318 319
#ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
  if (stack_size)
320 321
    {
      stack_size = MAX (g_thread_min_stack_size, stack_size);
322 323 324
      /* No error check here, because some systems can't do it and
       * we simply don't want threads to fail because of that. */
      pthread_attr_setstacksize (&attr, stack_size);
325
    }
326 327
#endif /* HAVE_PTHREAD_ATTR_SETSTACKSIZE */

328
#ifdef PTHREAD_SCOPE_SYSTEM
329
  if (bound)
330 331 332
    /* No error check here, because some systems can't do it and we
     * simply don't want threads to fail because of that. */
    pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM);
333
#endif /* PTHREAD_SCOPE_SYSTEM */
334

335
#ifdef G_THREADS_IMPL_POSIX
336
  posix_check_cmd (pthread_attr_setdetachstate (&attr,
337 338
          joinable ? PTHREAD_CREATE_JOINABLE : PTHREAD_CREATE_DETACHED));
#endif /* G_THREADS_IMPL_POSIX */
339

340 341
#ifdef HAVE_PRIORITIES
# ifdef G_THREADS_IMPL_POSIX
342 343
  {
    struct sched_param sched;
344
    posix_check_cmd (pthread_attr_getschedparam (&attr, &sched));
345
    sched.sched_priority = g_thread_priority_map [priority];
346
    posix_check_cmd_prio (pthread_attr_setschedparam (&attr, &sched));
347
  }
348
# else /* G_THREADS_IMPL_DCE */
349
  posix_check_cmd_prio
350
    (pthread_attr_setprio (&attr, g_thread_priority_map [priority]));
351 352
# endif /* G_THREADS_IMPL_DCE */
#endif /* HAVE_PRIORITIES */
353
  ret = posix_error (pthread_create (thread, &attr,
354
				     (void* (*)(void*))thread_func, arg));
355

356
  posix_check_cmd (pthread_attr_destroy (&attr));
357

358
  if (ret == EAGAIN)
359 360 361 362 363 364
    {
      g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN, 
		   "Error creating thread: %s", g_strerror (ret));
      return;
    }

365
  posix_check_err (ret, "pthread_create");
366

367 368
#ifdef G_THREADS_IMPL_DCE
  if (!joinable)
369
    posix_check_cmd (pthread_detach (thread));
370
#endif /* G_THREADS_IMPL_DCE */
371 372
}

373
static void
374 375 376 377 378
g_thread_yield_posix_impl (void)
{
  POSIX_YIELD_FUNC;
}

379
static void
380
g_thread_join_posix_impl (gpointer thread)
381
{
382
  gpointer ignore;
383
  posix_check_cmd (pthread_join (*(pthread_t*)thread, &ignore));
384 385
}

386 387
static void
g_thread_exit_posix_impl (void)
388 389
{
  pthread_exit (NULL);
390 391
}

392
static void
393 394
g_thread_set_priority_posix_impl (gpointer thread, GThreadPriority priority)
{
395 396
  g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
  g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);
397 398
#ifdef HAVE_PRIORITIES
# ifdef G_THREADS_IMPL_POSIX
399 400 401
  {
    struct sched_param sched;
    int policy;
402
    posix_check_cmd (pthread_getschedparam (*(pthread_t*)thread, &policy,
403 404
					    &sched));
    sched.sched_priority = g_thread_priority_map [priority];
405
    posix_check_cmd_prio (pthread_setschedparam (*(pthread_t*)thread, policy,
406 407
						 &sched));
  }
408
# else /* G_THREADS_IMPL_DCE */
409
  posix_check_cmd_prio (pthread_setprio (*(pthread_t*)thread,
410
					 g_thread_priority_map [priority]));
411
# endif
412
#endif /* HAVE_PRIORITIES */
413 414
}

415 416 417 418 419
static void
g_thread_self_posix_impl (gpointer thread)
{
  *(pthread_t*)thread = pthread_self();
}
420

421 422 423 424 425 426
static gboolean
g_thread_equal_posix_impl (gpointer thread1, gpointer thread2)
{
  return (pthread_equal (*(pthread_t*)thread1, *(pthread_t*)thread2) != 0);
}

427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
static guint64
g_gettime_posix_impl (void)
{
#ifdef USE_CLOCK_GETTIME 
  struct timespec tv;

  clock_gettime (posix_clock, &tv);

  return tv.tv_sec * 1e9 + tv.tv_nsec;
#else
  struct timeval tv;

  gettimeofday (&tv, NULL);

  return tv.tv_sec * 1e9 + tv.tv_usec * 1000; 
#endif
}

445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
static GThreadFunctions g_thread_functions_for_glib_use_default =
{
  g_mutex_new_posix_impl,
  (void (*)(GMutex *)) pthread_mutex_lock,
  g_mutex_trylock_posix_impl,
  (void (*)(GMutex *)) pthread_mutex_unlock,
  g_mutex_free_posix_impl,
  g_cond_new_posix_impl,
  (void (*)(GCond *)) pthread_cond_signal,
  (void (*)(GCond *)) pthread_cond_broadcast,
  (void (*)(GCond *, GMutex *)) pthread_cond_wait,
  g_cond_timed_wait_posix_impl,
  g_cond_free_posix_impl,
  g_private_new_posix_impl,
  g_private_get_posix_impl,
460 461 462 463 464 465
  g_private_set_posix_impl,
  g_thread_create_posix_impl,
  g_thread_yield_posix_impl,
  g_thread_join_posix_impl,
  g_thread_exit_posix_impl,
  g_thread_set_priority_posix_impl,
466
  g_thread_self_posix_impl,
467 468
  g_thread_equal_posix_impl,
  g_gettime_posix_impl
469
};