1 /* xbt_os_thread -- portability layer over the pthread API */
2 /* Used in RL to get win/lin portability, and in SG when CONTEXT_THREAD */
3 /* in SG, when using HAVE_UCONTEXT_CONTEXTS, xbt_os_thread_stub is used instead */
5 /* Copyright (c) 2007-2019. The SimGrid Team. All rights reserved. */
7 /* This program is free software; you can redistribute it and/or modify it
8 * under the terms of the license (GNU LGPL) which comes with this package. */
10 #include "src/internal_config.h"
11 #if HAVE_PTHREAD_SETAFFINITY
19 #include <semaphore.h>
24 #elif defined(__MACH__) && defined(__APPLE__)
26 #include <sys/types.h>
27 #include <sys/sysctl.h>
32 #include "xbt/sysdep.h"
34 #include "src/internal_config.h"
35 #include "xbt/xbt_os_time.h" /* Portable time facilities */
36 #include "xbt/xbt_os_thread.h" /* This module */
37 #include "src/xbt_modinter.h" /* Initialization/finalization of this module */
39 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_sync_os, xbt, "Synchronization mechanism (OS-level)");
41 typedef struct xbt_os_thread_ {
44 pvoid_f_pvoid_t start_routine;
47 /** Calls pthread_atfork() if present, and raise an exception otherwise.
49 * The only known user of this wrapper is mmalloc_preinit(), but it is absolutely mandatory there:
50 * when used with tesh, mmalloc *must* be mutex protected and resistant to forks.
51 * This functionality is the only way to get it working (by ensuring that the mutex is consistently released on forks)
54 /* this function is critical to tesh+mmalloc, don't mess with it */
55 int xbt_os_thread_atfork(void (*prepare)(void), void (*parent)(void), void (*child)(void))
57 return pthread_atfork(prepare, parent, child);
60 /****** mutex related functions ******/
61 typedef struct xbt_os_mutex_ {
68 xbt_os_mutex_t xbt_os_mutex_init(void)
70 pthread_mutexattr_t Attr;
71 pthread_mutexattr_init(&Attr);
72 pthread_mutexattr_settype(&Attr, PTHREAD_MUTEX_RECURSIVE);
74 xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t, 1);
75 int errcode = pthread_mutex_init(&(res->m), &Attr);
76 xbt_assert(errcode==0, "pthread_mutex_init() failed: %s", strerror(errcode));
81 void xbt_os_mutex_acquire(xbt_os_mutex_t mutex)
83 int errcode = pthread_mutex_lock(&(mutex->m));
84 xbt_assert(errcode==0, "pthread_mutex_lock(%p) failed: %s", mutex, strerror(errcode));
87 void xbt_os_mutex_release(xbt_os_mutex_t mutex)
89 int errcode = pthread_mutex_unlock(&(mutex->m));
90 xbt_assert(errcode==0, "pthread_mutex_unlock(%p) failed: %s", mutex, strerror(errcode));
93 void xbt_os_mutex_destroy(xbt_os_mutex_t mutex)
98 int errcode = pthread_mutex_destroy(&(mutex->m));
99 xbt_assert(errcode == 0, "pthread_mutex_destroy(%p) failed: %s", mutex, strerror(errcode));