C++ – Logging safely from a worker thread

cmultithreading

In one of my worker threads I want to do some logging. The log messages are channeled to a GUI textarea, which should only be accessed from the main thread. So the problem is: how do I log messages safely from a worker thread?

My current solution is to have the logging function check whether we are currently in the main thread. If yes, then just log. If no, then add the message to a queue of pending messages (this queue is protected by a mutex). The main thread also has a timer who's callback function (which also executes in the main thread) takes care of dequeueing and logging any pending messages.

Above solution is just my own little invention. Are there better or more standard solutions to this problem?

Best Answer

If you have one rule for logging in one thread ("just do it now") and another rule for other threads ("add it to a queue for later") then your logging will get out of order. I can't imagine this being a good thing. Have one rule for all your logging - add it to the queue.