diff --git a/printf.c b/printf.c index 8a700add..fa0f06e9 100644 --- a/printf.c +++ b/printf.c @@ -95,6 +95,12 @@ #define PRINTF_SUPPORT_PTRDIFF_T #endif +// add lock and unlock functions to protect io operations +// default: deactivated +#ifdef PRINTF_ENABLE_LOCK +#define PRINTF_IO_LOCK +#endif + /////////////////////////////////////////////////////////////////////////////// // internal flag definitions @@ -861,11 +867,17 @@ static int _vsnprintf(out_fct_type out, char* buffer, const size_t maxlen, const int printf_(const char* format, ...) { +#if defined(PRINTF_IO_LOCK) + __io_lock(); +#endif va_list va; va_start(va, format); char buffer[1]; const int ret = _vsnprintf(_out_char, buffer, (size_t)-1, format, va); va_end(va); +#if defined(PRINTF_IO_LOCK) + __io_unlock(); +#endif return ret; } diff --git a/printf.h b/printf.h index 6104ccfb..6b2cf5c9 100644 --- a/printf.h +++ b/printf.h @@ -40,6 +40,21 @@ extern "C" { #endif +/** + * Lock the printf to avoid collision when multiple threads/cores try to output strings/characters. + * This function can implement a mutex, semaphore or whatever lock. + * + * \note PRINTF_ENABLE_LOCK should be defined in order to activate lock function. + */ +void __io_lock(); + +/** + * Unlock the printf, release the lock, semaphore or mutex used to lock printf. + * This function releases the mutex, semaphore or whatever lock used previously. + * + * \note PRINTF_ENABLE_LOCK should be defined in order to activate unlock function. + */ +void __io_unlock(); /** * Output a character to a custom device like UART, used by the printf() function