From b0fc1912eab251175659cb18dcdcd40bd116f465 Mon Sep 17 00:00:00 2001 From: whitequark Date: Wed, 22 Jul 2020 11:04:48 +0000 Subject: [PATCH] Create mimalloc heaps only when necessary. The mimalloc temporary heap is a thread-local object that uses RAII to manage heap lifetimes even in threads that are created implicitly, e.g. by OpenMP. However, not all threads are necessarily created by the application; graphics drivers may create their own threads, and this can lead to deadlocks when combined with library unloading. Fixes #657. --- src/platform/platform.cpp | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/platform/platform.cpp b/src/platform/platform.cpp index 934220c..a080982 100644 --- a/src/platform/platform.cpp +++ b/src/platform/platform.cpp @@ -684,20 +684,21 @@ void DebugPrint(const char *fmt, ...) { //----------------------------------------------------------------------------- struct MimallocHeap { - mi_heap_t *heap = mi_heap_new(); - - MimallocHeap() { - ssassert(heap != NULL, "out of memory"); - } + mi_heap_t *heap = NULL; ~MimallocHeap() { - mi_heap_destroy(heap); + if(heap != NULL) + mi_heap_destroy(heap); } }; static thread_local MimallocHeap TempArena; void *AllocTemporary(size_t size) { + if(TempArena.heap == NULL) { + TempArena.heap = mi_heap_new(); + ssassert(TempArena.heap != NULL, "out of memory"); + } void *ptr = mi_heap_zalloc(TempArena.heap, size); ssassert(ptr != NULL, "out of memory"); return ptr;