Synchronize access to the log's output stream with a mutex and document the write() method as being thread-safe.

This commit is contained in:
Robert Knight 2011-09-02 23:32:45 +01:00
parent e2d3acf850
commit 9c260bc114
2 changed files with 9 additions and 0 deletions

View File

@ -24,7 +24,9 @@ Log::~Log()
void Log::open(const std::string& path)
{
m_mutex.lock();
m_output.open(path.c_str(),std::ios_base::out | std::ios_base::app);
m_mutex.unlock();
}
void Log::writeToStream(std::ostream& stream, Type type, const char* text)
@ -46,10 +48,12 @@ void Log::writeToStream(std::ostream& stream, Type type, const char* text)
void Log::write(Type type, const char* text)
{
m_mutex.lock();
writeToStream(std::cerr,type,text);
if (m_output.is_open())
{
writeToStream(m_output,type,text);
}
m_mutex.unlock();
}

View File

@ -3,6 +3,8 @@
#include <string>
#include <fstream>
#include "tinythread.h"
class Log
{
public:
@ -18,7 +20,9 @@ class Log
void open(const std::string& path);
/** Write @p text to the log. This method is thread-safe. */
void write(Type type, const std::string& text);
/** Write @p text to the log. This method is thread-safe. */
void write(Type type, const char* text);
static Log* instance();
@ -26,6 +30,7 @@ class Log
private:
static void writeToStream(std::ostream& stream, Type type, const char* text);
tthread::mutex m_mutex;
std::ofstream m_output;
};