From 608a66b867d8c4ceb9df269b1e04f3e39af9f2ec Mon Sep 17 00:00:00 2001 From: Johannes Demel Date: Thu, 4 Mar 2021 22:14:48 +0100 Subject: [PATCH] prefs: Introduce mutex for thread-safety We initialize a mutex with `call_once` and then use this mutex to protect the init and deinit portion of our struct handlers. Signed-off-by: Johannes Demel --- lib/CMakeLists.txt | 1 + lib/volk_prefs.c | 23 ++++++++++++++++++++--- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/lib/CMakeLists.txt b/lib/CMakeLists.txt index a27be22b4..4b9b0c990 100644 --- a/lib/CMakeLists.txt +++ b/lib/CMakeLists.txt @@ -560,6 +560,7 @@ if(ORC_FOUND) endif() if(NOT MSVC) target_link_libraries(volk PUBLIC m) + target_link_libraries(volk PRIVATE pthread) endif() set_target_properties(volk PROPERTIES VERSION ${VERSION}) set_target_properties(volk PROPERTIES SOVERSION ${SOVERSION}) diff --git a/lib/volk_prefs.c b/lib/volk_prefs.c index 5ca0ddfee..733b6f25b 100644 --- a/lib/volk_prefs.c +++ b/lib/volk_prefs.c @@ -18,7 +18,7 @@ #else #include #endif -#include +#include #include void volk_get_config_path(char* path, bool read) @@ -77,27 +77,44 @@ void volk_get_config_path(char* path, bool read) static struct volk_preferences { volk_arch_pref_t* volk_arch_prefs; size_t n_arch_prefs; - atomic_int initialized; + int initialized; + mtx_t mutex; } volk_preferences; +void init_struct_mutex(void) +{ + if (mtx_init(&volk_preferences.mutex, mtx_plain) != thrd_success) { + printf("\n mutex init failed\n"); + } +} + +static once_flag mutex_init_once_flag = ONCE_FLAG_INIT; +void initialize_mutex() { call_once(&mutex_init_once_flag, init_struct_mutex); } void volk_initialize_preferences() { - if (!atomic_fetch_and(&volk_preferences.initialized, 1)) { + initialize_mutex(); + mtx_lock(&volk_preferences.mutex); + if (!volk_preferences.initialized) { volk_preferences.n_arch_prefs = volk_load_preferences(&volk_preferences.volk_arch_prefs); + volk_preferences.initialized = 1; } + mtx_unlock(&volk_preferences.mutex); } void volk_free_preferences() { + initialize_mutex(); + mtx_lock(&volk_preferences.mutex); if (volk_preferences.initialized) { free(volk_preferences.volk_arch_prefs); volk_preferences.n_arch_prefs = 0; volk_preferences.initialized = 0; } + mtx_unlock(&volk_preferences.mutex); }