Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add __io_lock() and __io_unlock() functions to lock io functions #67

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions printf.c
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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;
}

Expand Down
15 changes: 15 additions & 0 deletions printf.h
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should these be wrapped in PRINTF_IO_LOCK preprocessor checks?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually was using the format introduced by Marco to enable features.
Here PRINTF_ENABLE_LOCK is a macro to add in Makefile, and if it is defined, then PRINTF_IO_LOCK will be enabled and lock and unlock functions activated.


/**
* 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
Expand Down