I have this code for some proprietary logger:
#define LOG GetStream()
Where GetStream returns an std::ostream. User will do:
LOG << "text";
I need this to be thread safe but would like to avoid this:
#define END Unlock();
#define LOG Lock(); GetStream() << "text" << END;
Since user will need to add the "END":
LOG << "Text" << END;
Any ideas?
Remark: I handle the carriage return using something like this.
One way to solve this is to use function-style macros, where you incorporate the locking/unlocking by using a C++ block and scoping:
The
LockingClass
(or whatever you want to name it) is a scoped lock, which locks the stream on construction, and unlocks it in on destruction.Could be used like e.g.
Can't use it with expressions containing comma though, the preprocessor will interpret commas as argument separator for the macro. Could probably be solved with variadic macros.