Skip to content

Commit b2e93c5

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 3e3d08d commit b2e93c5

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
@@ -555,6 +555,7 @@ if(ORC_FOUND)
555555
endif()
556556
if(NOT MSVC)
557557
target_link_libraries(volk PUBLIC m)
558+
target_link_libraries(volk PRIVATE pthread)
558559
endif()
559560
set_target_properties(volk PROPERTIES SOVERSION ${LIBVER})
560561
set_target_properties(volk PROPERTIES DEFINE_SYMBOL "volk_EXPORTS")

lib/volk_prefs.c

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
#else
1010
#include <unistd.h>
1111
#endif
12-
#include <stdatomic.h>
12+
#include <threads.h>
1313
#include <volk/volk_prefs.h>
1414

1515
void volk_get_config_path(char* path, bool read)
@@ -68,27 +68,44 @@ void volk_get_config_path(char* path, bool read)
6868
static struct volk_preferences {
6969
volk_arch_pref_t* volk_arch_prefs;
7070
size_t n_arch_prefs;
71-
atomic_int initialized;
71+
int initialized;
72+
mtx_t mutex;
7273

7374
} volk_preferences;
7475

76+
void init_struct_mutex(void)
77+
{
78+
if (mtx_init(&volk_preferences.mutex, mtx_plain) != thrd_success) {
79+
printf("\n mutex init failed\n");
80+
}
81+
}
82+
83+
static once_flag mutex_init_once_flag = ONCE_FLAG_INIT;
84+
void initialize_mutex() { call_once(&mutex_init_once_flag, init_struct_mutex); }
7585

7686
void volk_initialize_preferences()
7787
{
78-
if (!atomic_fetch_and(&volk_preferences.initialized, 1)) {
88+
initialize_mutex();
89+
mtx_lock(&volk_preferences.mutex);
90+
if (!volk_preferences.initialized) {
7991
volk_preferences.n_arch_prefs =
8092
volk_load_preferences(&volk_preferences.volk_arch_prefs);
93+
volk_preferences.initialized = 1;
8194
}
95+
mtx_unlock(&volk_preferences.mutex);
8296
}
8397

8498

8599
void volk_free_preferences()
86100
{
101+
initialize_mutex();
102+
mtx_lock(&volk_preferences.mutex);
87103
if (volk_preferences.initialized) {
88104
free(volk_preferences.volk_arch_prefs);
89105
volk_preferences.n_arch_prefs = 0;
90106
volk_preferences.initialized = 0;
91107
}
108+
mtx_unlock(&volk_preferences.mutex);
92109
}
93110

94111

0 commit comments

Comments
 (0)