Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Basic logging macro has mutex and scoped lock but lines are getting interlaced

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading