From f89c6ad90c700bbc03003bf423aaff4f496f34dc Mon Sep 17 00:00:00 2001 From: Jeff Lawson Date: Sat, 3 Feb 2024 18:45:48 -0800 Subject: [PATCH] Added mutex lock around logging, so multi-core can log synchronized --- ArduinoLog.cpp | 2 ++ ArduinoLog.h | 53 +++++++++++++++++++++++++++----------------------- 2 files changed, 31 insertions(+), 24 deletions(-) diff --git a/ArduinoLog.cpp b/ArduinoLog.cpp index c4075fe..b4b34f4 100644 --- a/ArduinoLog.cpp +++ b/ArduinoLog.cpp @@ -37,6 +37,8 @@ void Logging::begin(int level, Print* logOutput, bool showLevel) setLevel(level); setShowLevel(showLevel); _logOutput = logOutput; + _semaphore = xSemaphoreCreateMutex(); + xSemaphoreGive(_semaphore); #endif } diff --git a/ArduinoLog.h b/ArduinoLog.h index 9ec9fb0..3acfc40 100644 --- a/ArduinoLog.h +++ b/ArduinoLog.h @@ -14,6 +14,7 @@ Licensed under the MIT License . #pragma once #include #include +#include // Non standard: Arduino.h also chosen if ARDUINO is not defined. To facilitate use in non-Arduino test environments #if ARDUINO < 100 @@ -346,30 +347,33 @@ class Logging { level = LOG_LEVEL_SILENT; } - - - if (_prefix != NULL) - { - _prefix(_logOutput, level); - } - - if (_showLevel) { - static const char levels[] = "FEWITV"; - _logOutput->print(levels[level - 1]); - _logOutput->print(": "); - } - - va_list args; - va_start(args, msg); - print(msg, args); - - if(_suffix != NULL) - { - _suffix(_logOutput, level); - } - if (cr) - { - _logOutput->print(CR); + + if(xSemaphoreTake(_semaphore, (TickType_t) 10 )) { + + if (_prefix != NULL) + { + _prefix(_logOutput, level); + } + + if (_showLevel) { + static const char levels[] = "FEWITV"; + _logOutput->print(levels[level - 1]); + _logOutput->print(": "); + } + + va_list args; + va_start(args, msg); + print(msg, args); + + if(_suffix != NULL) + { + _suffix(_logOutput, level); + } + if (cr) + { + _logOutput->print(CR); + } + xSemaphoreGive(_semaphore); } #endif } @@ -378,6 +382,7 @@ class Logging int _level; bool _showLevel; Print* _logOutput; + SemaphoreHandle_t _semaphore; printfunction _prefix = NULL; printfunction _suffix = NULL;