Skip to content

Commit

Permalink
prefs: Introduce mutex for thread-safety
Browse files Browse the repository at this point in the history
We initialize a mutex with `call_once` and then use this mutex to
protect the init and deinit portion of our struct handlers.
  • Loading branch information
jdemel committed Mar 4, 2021
1 parent 3e3d08d commit 5135444
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
1 change: 1 addition & 0 deletions lib/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -555,6 +555,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 SOVERSION ${LIBVER})
set_target_properties(volk PROPERTIES DEFINE_SYMBOL "volk_EXPORTS")
Expand Down
23 changes: 20 additions & 3 deletions lib/volk_prefs.c
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
#else
#include <unistd.h>
#endif
#include <stdatomic.h>
#include <threads.h>
#include <volk/volk_prefs.h>

void volk_get_config_path(char* path, bool read)
Expand Down Expand Up @@ -68,27 +68,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);
}


Expand Down

0 comments on commit 5135444

Please sign in to comment.