I have a really basic macro for logging. It is called by multiple threads.
I thought adding the mutex and scoped_lock would ensure the output does not get inter-mingled by the threads. However, the lines output in the Linux terminal are getting corrupted by the various threads.
What can I change to ensure the output shows a complete line without any corruption? Is there something simple I am missing?
#define LOG2(msg) \
do \
{ \
static std::mutex mutex; \
std::scoped_lock<std::mutex> lock(mutex); \
{ \
std::cout << mynow() << " " << std::boolalpha << msg << std::endl; \
} \
} while (false)
>Solution :
Each call to your macro is declaring a different mutex object; that is why the synchronization isn’t working. You need to instead declare a single mutex object that is used by all of the calls.
Simply declaring the mutex static isn’t enough because each macro invocation is in its own scope, so you end up with a separate static-variable for each invocation.
The easiest fix would be to convert your macro into a function; then it would behave the way you want.