From 4aa0fab4f424fb5ccd7571c8968f45a2af5ea534 Mon Sep 17 00:00:00 2001 From: Daniel Micay Date: Thu, 23 Aug 2018 17:15:50 -0400 Subject: [PATCH] avoid deadlocks after forking threaded processes --- malloc.c | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/malloc.c b/malloc.c index fbd7229..d46ef33 100644 --- a/malloc.c +++ b/malloc.c @@ -525,6 +525,31 @@ static void regions_delete(struct region_info *region) { } } +static void pre_fork(void) { + pthread_mutex_lock(®ions_lock); + for (unsigned i = 0; i < N_SIZE_CLASSES; i++) { + pthread_mutex_lock(&size_class_metadata[i].mutex); + } +} + +static void post_fork_parent(void) { + pthread_mutex_unlock(®ions_lock); + for (unsigned i = 0; i < N_SIZE_CLASSES; i++) { + pthread_mutex_unlock(&size_class_metadata[i].mutex); + } +} + +static void post_fork_child(void) { + if (pthread_mutex_init(®ions_lock, NULL)) { + fatal_error("mutex initialization failed"); + } + for (unsigned i = 0; i < N_SIZE_CLASSES; i++) { + if (pthread_mutex_init(&size_class_metadata[i].mutex, NULL)) { + fatal_error("mutex initialization failed"); + } + } +} + COLD static void init_slow_path(void) { static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; @@ -535,6 +560,8 @@ COLD static void init_slow_path(void) { return; } + pthread_atfork(pre_fork, post_fork_parent, post_fork_child); + struct random_state rng; random_state_init(&rng);