I developed a logger for testing our modules in c++, Win32 console, visual studio(Windows)
Logger is running in one thread.
While it displays output in console window, thread is getting preempted.
Some other module thread is running.
So output of other modules is getting mixed with output of Logger module in Console window.
Is there any way to avoid preemption of logger thread, so that entire logger output can be at one place in console output window ?
Writing to file instead of output window is one solution. But as the drive names may be different on different machines, its difficult to hardcode the logger output file path. Even then, we can still write the code for finding the drives available on any machine and write to first drive etc. But tester may not understand where to search for the logger output file.
The standard solution is to use a mutex . After formatting, but before starting the output to the console, you lock the mutex. When all output is sent, you unlock the mutex again. If a second thread comes in, its attempt to lock the mutex will cause that thread to be preempted until the first thread is done.
CriticalSections in Windows behave mutex-like and are also usable. They use a slightly different terminology. You don’t “lock” them, you “enter” and “leave” a critical section with
EnterCriticalSectionandLeaveCriticalSection.