I have a multi-threaded application, which heavily uses std::cout
for logging without any locking. In such a case, how can I easily add lock mechanism to make <
I really like the trick from Nicolás given in this question of creating a temporary object and putting the protection code on the destructor.
/** Thread safe cout class
* Exemple of use:
* PrintThread{} << "Hello world!" << std::endl;
*/
class PrintThread: public std::ostringstream
{
public:
PrintThread() = default;
~PrintThread()
{
std::lock_guard guard(_mutexPrint);
std::cout << this->str();
}
private:
static std::mutex _mutexPrint;
};
std::mutex PrintThread::_mutexPrint{};
You can then use it as a regular std::cout
, from any thread:
PrintThread{} << "my_val=" << val << std::endl;
The object collect data as a regular ostringstream
. As soon the coma is reached, the object is destroyed and flush all collected information.