Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Make mallocators thread-safe
authorArnaud Legrand <arnaud.legrand@imag.fr>
Mon, 26 Mar 2012 20:19:58 +0000 (22:19 +0200)
committerArnaud Legrand <arnaud.legrand@imag.fr>
Mon, 26 Mar 2012 20:20:48 +0000 (22:20 +0200)
src/xbt/mallocator.c
src/xbt/mallocator_private.h

index ed415a5..e121b32 100644 (file)
@@ -68,7 +68,7 @@ xbt_mallocator_t xbt_mallocator_new(int size,
     m->objects = NULL;
     m->max_size = 0;
   }
-
+  m->mutex = xbt_os_mutex_init();
   return m;
 }
 
@@ -92,6 +92,7 @@ void xbt_mallocator_free(xbt_mallocator_t m)
     m->free_f(m->objects[i]);
   }
   xbt_free(m->objects);
+  xbt_os_mutex_destroy(m->mutex);
   xbt_free(m);
 }
 
@@ -116,6 +117,7 @@ void *xbt_mallocator_get(xbt_mallocator_t m)
   void *object;
 
   if (MALLOCATOR_IS_ENABLED) {
+    xbt_os_mutex_acquire(m->mutex);
     if (m->current_size <= 0) {
       /* No object is ready yet. Create a bunch of them to try to group the
        * mallocs on the same memory pages (to help the cache lines) */
@@ -133,6 +135,7 @@ void *xbt_mallocator_get(xbt_mallocator_t m)
     /* XBT_DEBUG("Reuse an old object for mallocator %p (size:%d/%d)", */
     /*           m, m->current_size, m->max_size); */
     object = m->objects[--m->current_size];
+    xbt_os_mutex_release(m->mutex);
   } else {
     object = m->new_f();
   }
@@ -157,6 +160,7 @@ void *xbt_mallocator_get(xbt_mallocator_t m)
  */
 void xbt_mallocator_release(xbt_mallocator_t m, void *object)
 {
+  xbt_os_mutex_acquire(m->mutex);
   if (m->current_size < m->max_size) {
     /* there is enough place to push the object */
     /* XBT_DEBUG
@@ -169,4 +173,5 @@ void xbt_mallocator_release(xbt_mallocator_t m, void *object)
            m->current_size, m->max_size); */
     m->free_f(object);
   }
+  xbt_os_mutex_release(m->mutex);
 }
index 8748245..12cccbf 100644 (file)
@@ -8,7 +8,7 @@
 
 #ifndef _XBT_MALLOCATOR_PRIVATE_H__
 #define _XBT_MALLOCATOR_PRIVATE_H__
-
+#include "xbt/xbt_os_thread.h"
 typedef struct s_xbt_mallocator {
   void **objects;               /* objects stored by the mallocator and available for the user */
   int current_size;             /* number of objects currently stored */
@@ -16,6 +16,7 @@ typedef struct s_xbt_mallocator {
   pvoid_f_void_t new_f;         /* function to call when we are running out of objects */
   void_f_pvoid_t free_f;        /* function to call when we have got too many objects */
   void_f_pvoid_t reset_f;       /* function to call when an object is released by the user */
+  xbt_os_mutex_t mutex;         /* mutex to ensure the mallocator is thread-safe */
 } s_xbt_mallocator_t;
 
 #endif                          /* _XBT_MALLOCATOR_PRIVATE_H__ */