Skip to content

Commit f89c6ad

Browse files
committed
Added mutex lock around logging, so multi-core can log synchronized
1 parent 3f4fcf5 commit f89c6ad

File tree

2 files changed

+31
-24
lines changed

2 files changed

+31
-24
lines changed

ArduinoLog.cpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ void Logging::begin(int level, Print* logOutput, bool showLevel)
3737
setLevel(level);
3838
setShowLevel(showLevel);
3939
_logOutput = logOutput;
40+
_semaphore = xSemaphoreCreateMutex();
41+
xSemaphoreGive(_semaphore);
4042
#endif
4143
}
4244

ArduinoLog.h

Lines changed: 29 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ Licensed under the MIT License <http://opensource.org/licenses/MIT>.
1414
#pragma once
1515
#include <inttypes.h>
1616
#include <stdarg.h>
17+
#include <mutex>
1718

1819
// Non standard: Arduino.h also chosen if ARDUINO is not defined. To facilitate use in non-Arduino test environments
1920
#if ARDUINO < 100
@@ -346,30 +347,33 @@ class Logging
346347
{
347348
level = LOG_LEVEL_SILENT;
348349
}
349-
350-
351-
if (_prefix != NULL)
352-
{
353-
_prefix(_logOutput, level);
354-
}
355-
356-
if (_showLevel) {
357-
static const char levels[] = "FEWITV";
358-
_logOutput->print(levels[level - 1]);
359-
_logOutput->print(": ");
360-
}
361-
362-
va_list args;
363-
va_start(args, msg);
364-
print(msg, args);
365-
366-
if(_suffix != NULL)
367-
{
368-
_suffix(_logOutput, level);
369-
}
370-
if (cr)
371-
{
372-
_logOutput->print(CR);
350+
351+
if(xSemaphoreTake(_semaphore, (TickType_t) 10 )) {
352+
353+
if (_prefix != NULL)
354+
{
355+
_prefix(_logOutput, level);
356+
}
357+
358+
if (_showLevel) {
359+
static const char levels[] = "FEWITV";
360+
_logOutput->print(levels[level - 1]);
361+
_logOutput->print(": ");
362+
}
363+
364+
va_list args;
365+
va_start(args, msg);
366+
print(msg, args);
367+
368+
if(_suffix != NULL)
369+
{
370+
_suffix(_logOutput, level);
371+
}
372+
if (cr)
373+
{
374+
_logOutput->print(CR);
375+
}
376+
xSemaphoreGive(_semaphore);
373377
}
374378
#endif
375379
}
@@ -378,6 +382,7 @@ class Logging
378382
int _level;
379383
bool _showLevel;
380384
Print* _logOutput;
385+
SemaphoreHandle_t _semaphore;
381386

382387
printfunction _prefix = NULL;
383388
printfunction _suffix = NULL;

0 commit comments

Comments
 (0)