Skip to content

Commit 608a66b

Browse files
committed
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 <[email protected]>
1 parent e355e59 commit 608a66b

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

lib/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -560,6 +560,7 @@ if(ORC_FOUND)
560560
endif()
561561
if(NOT MSVC)
562562
target_link_libraries(volk PUBLIC m)
563+
target_link_libraries(volk PRIVATE pthread)
563564
endif()
564565
set_target_properties(volk PROPERTIES VERSION ${VERSION})
565566
set_target_properties(volk PROPERTIES SOVERSION ${SOVERSION})

lib/volk_prefs.c

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
#else
1919
#include <unistd.h>
2020
#endif
21-
#include <stdatomic.h>
21+
#include <threads.h>
2222
#include <volk/volk_prefs.h>
2323

2424
void volk_get_config_path(char* path, bool read)
@@ -77,27 +77,44 @@ void volk_get_config_path(char* path, bool read)
7777
static struct volk_preferences {
7878
volk_arch_pref_t* volk_arch_prefs;
7979
size_t n_arch_prefs;
80-
atomic_int initialized;
80+
int initialized;
81+
mtx_t mutex;
8182

8283
} volk_preferences;
8384

85+
void init_struct_mutex(void)
86+
{
87+
if (mtx_init(&volk_preferences.mutex, mtx_plain) != thrd_success) {
88+
printf("\n mutex init failed\n");
89+
}
90+
}
91+
92+
static once_flag mutex_init_once_flag = ONCE_FLAG_INIT;
93+
void initialize_mutex() { call_once(&mutex_init_once_flag, init_struct_mutex); }
8494

8595
void volk_initialize_preferences()
8696
{
87-
if (!atomic_fetch_and(&volk_preferences.initialized, 1)) {
97+
initialize_mutex();
98+
mtx_lock(&volk_preferences.mutex);
99+
if (!volk_preferences.initialized) {
88100
volk_preferences.n_arch_prefs =
89101
volk_load_preferences(&volk_preferences.volk_arch_prefs);
102+
volk_preferences.initialized = 1;
90103
}
104+
mtx_unlock(&volk_preferences.mutex);
91105
}
92106

93107

94108
void volk_free_preferences()
95109
{
110+
initialize_mutex();
111+
mtx_lock(&volk_preferences.mutex);
96112
if (volk_preferences.initialized) {
97113
free(volk_preferences.volk_arch_prefs);
98114
volk_preferences.n_arch_prefs = 0;
99115
volk_preferences.initialized = 0;
100116
}
117+
mtx_unlock(&volk_preferences.mutex);
101118
}
102119

103120

0 commit comments

Comments
 (0)