From 35ed2d51381539a2415b84d75c6f4193038f84ce Mon Sep 17 00:00:00 2001 From: Andreas Eversberg Date: Wed, 15 Sep 2021 12:28:29 +0200 Subject: [PATCH] Added locking to debug output, to prevent race condition between threads --- configure.ac | 4 ++-- src/libdebug/debug.c | 22 +++++++++++++++++++--- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/configure.ac b/configure.ac index 16f631f..853be7e 100644 --- a/configure.ac +++ b/configure.ac @@ -24,8 +24,8 @@ dnl Checks for typedefs, structures and compiler characteristics AC_CANONICAL_HOST -AC_CHECK_LIB([m], [main]) -AC_CHECK_LIB([pthread], [main]) +AC_CHECK_LIB([m], [main], [], [echo "Failed to find lib!" ; exit -1]) +AC_CHECK_LIB([pthread], [main], [], [echo "Failed to find lib!" ; exit -1]) with_sdr=no soapy_0_7_1_or_higher= diff --git a/src/libdebug/debug.c b/src/libdebug/debug.c index 5becb02..4593e8a 100755 --- a/src/libdebug/debug.c +++ b/src/libdebug/debug.c @@ -25,6 +25,7 @@ #include #include #include +#include #include #include #include "debug.h" @@ -100,6 +101,9 @@ void (*print_console_text)(void) = NULL; int debug_limit_scroll = 0; +static int lock_initialized = 0; +static pthread_mutex_t debug_mutex; + void get_win_size(int *w, int *h) { struct winsize win; @@ -123,10 +127,22 @@ void _printdebug(const char *file, const char __attribute__((unused)) *function, const char *p; va_list args; int w, h; + int rc; if (debuglevel > level) return; + if (!(debug_mask & ((uint64_t)1 << cat))) + return; + + if (!lock_initialized) { + rc = pthread_mutex_init(&debug_mutex, NULL); + if (rc == 0) + lock_initialized = 1; + } + if (lock_initialized) + pthread_mutex_lock(&debug_mutex); + buffer[sizeof(buffer) - 1] = '\0'; /* if kanal is used, prefix the channel number */ @@ -136,9 +152,6 @@ void _printdebug(const char *file, const char __attribute__((unused)) *function, s -= strlen(buffer); } - if (!(debug_mask & ((uint64_t)1 << cat))) - return; - va_start(args, fmt); vsnprintf(b, s, fmt, args); va_end(args); @@ -166,6 +179,9 @@ void _printdebug(const char *file, const char __attribute__((unused)) *function, if (print_console_text) print_console_text(); fflush(stdout); + + if (lock_initialized) + pthread_mutex_unlock(&debug_mutex); } const char *debug_amplitude(double level)