diff options
author | Andreas Eversberg <jolly@eversberg.eu> | 2021-09-15 12:28:29 +0200 |
---|---|---|
committer | Andreas Eversberg <jolly@eversberg.eu> | 2021-09-24 17:20:27 +0200 |
commit | 35ed2d51381539a2415b84d75c6f4193038f84ce (patch) | |
tree | 000ea9ee66369ac7df7c02978e82ef7a045078dd /src | |
parent | 1b16029ac663b612a29493fb0093377270af49fc (diff) |
Added locking to debug output, to prevent race condition between threads
Diffstat (limited to 'src')
-rwxr-xr-x | src/libdebug/debug.c | 22 |
1 files changed, 19 insertions, 3 deletions
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 <errno.h> #include <math.h> #include <time.h> +#include <pthread.h> #include <sys/ioctl.h> #include <sys/time.h> #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) |