From 4704e0da22d97812db790d70024cc2b4b1ffa791 Mon Sep 17 00:00:00 2001 From: Arnaud Legrand Date: Mon, 26 Mar 2012 22:19:58 +0200 Subject: [PATCH] Make mallocators thread-safe --- src/xbt/mallocator.c | 7 ++++++- src/xbt/mallocator_private.h | 3 ++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/xbt/mallocator.c b/src/xbt/mallocator.c index ed415a5ed7..e121b32015 100644 --- a/src/xbt/mallocator.c +++ b/src/xbt/mallocator.c @@ -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); } diff --git a/src/xbt/mallocator_private.h b/src/xbt/mallocator_private.h index 87482451c0..12cccbf5f1 100644 --- a/src/xbt/mallocator_private.h +++ b/src/xbt/mallocator_private.h @@ -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__ */ -- 2.20.1