Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Add functions xbt_os_thread_key_create, xbt_os_thread_get/set_specific
[simgrid.git] / src / xbt / xbt_os_thread.c
index 2efd81e..7d58f3e 100644 (file)
@@ -219,6 +219,24 @@ xbt_os_thread_t xbt_os_thread_self(void)
   return res;
 }
 
+void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
+
+  int errcode;
+  if ((errcode = pthread_key_create(key, NULL)))
+    THROWF(system_error, errcode, "pthread_key_create failed");
+}
+
+void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
+
+  int errcode;
+  if ((errcode = pthread_setspecific(key, value)))
+    THROWF(system_error, errcode, "pthread_setspecific failed");
+}
+
+void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
+  return pthread_getspecific(key);
+}
+
 void xbt_os_thread_detach(xbt_os_thread_t thread)
 {
   thread->detached = 1;
@@ -726,6 +744,21 @@ void xbt_os_thread_exit(int *retval)
     ExitThread(0);
 }
 
+void xbt_os_thread_key_create(xbt_os_thread_key_t* key) {
+
+  *key = TlsAlloc();
+}
+
+void xbt_os_thread_set_specific(xbt_os_thread_key_t key, void* value) {
+
+  if (!TlsSetValue(key, value))
+    THROWF(system_error, (int) GetLastError(), "TlsSetValue() failed");
+}
+
+void* xbt_os_thread_get_specific(xbt_os_thread_key_t key) {
+  return TlsGetValue(key);
+}
+
 void xbt_os_thread_detach(xbt_os_thread_t thread)
 {
   THROW_UNIMPLEMENTED;
@@ -1128,6 +1161,13 @@ void xbt_os_sem_get_value(xbt_os_sem_t sem, int *svalue)
 
 #endif
 
+/***** reentrant mutexes *****/
+typedef struct xbt_os_rmutex_ {
+  xbt_os_mutex_t mutex;
+  xbt_os_thread_t owner;
+  int count;
+} s_xbt_os_rmutex_t;
+
 void xbt_os_thread_set_extra_data(void *data)
 {
   xbt_os_thread_self()->extra_data = data;
@@ -1137,3 +1177,52 @@ void *xbt_os_thread_get_extra_data(void)
 {
   return xbt_os_thread_self()->extra_data;
 }
+
+xbt_os_rmutex_t xbt_os_rmutex_init(void)
+{
+  xbt_os_rmutex_t rmutex = xbt_new0(struct xbt_os_rmutex_, 0);
+  rmutex->mutex = xbt_os_mutex_init();
+  rmutex->owner = NULL;
+  rmutex->count = 0;
+  return rmutex;
+}
+
+void xbt_os_rmutex_acquire(xbt_os_rmutex_t rmutex)
+{
+  xbt_os_thread_t self = xbt_os_thread_self();
+
+  if (self == NULL) {
+    /* the thread module is not initialized yet */
+    rmutex->owner = NULL;
+    return;
+  }
+
+  if (self != rmutex->owner) {
+    xbt_os_mutex_acquire(rmutex->mutex);
+    rmutex->owner = self;
+    rmutex->count = 1;
+  } else {
+    rmutex->count++;
+ }
+}
+
+void xbt_os_rmutex_release(xbt_os_rmutex_t rmutex)
+{
+  if (rmutex->owner == NULL) {
+    /* the thread module was not initialized */
+    return;
+  }
+
+  xbt_assert(rmutex->owner == xbt_os_thread_self());
+
+  if (--rmutex->count == 0) {
+    rmutex->owner = NULL;
+    xbt_os_mutex_release(rmutex->mutex);
+  }
+}
+
+void xbt_os_rmutex_destroy(xbt_os_rmutex_t rmutex)
+{
+  xbt_os_mutex_destroy(rmutex->mutex);
+  xbt_free(rmutex);
+}