问题描述
我的工作我的引擎多线程日志记录。但我是个有麻烦使它MT。问题是,即使我深深复制我的Logger对象到一个局部变量,我将不得不与文件的问题。由于两个线程会在同一时间,这将建立一个烂摊子写入同一个文件。这里是我的记录器类:
I am working on a multithreaded logging for my engine. But I ma having troubles making it MT. The problem is, even if I am deep copying my logger object into a local variable I am going to have problems with the files. Because two threads are going to write to the same file at the same time which will build a mess. Here is my logger class:
class Logger {
public:
typedef std::vector<LogListener *> ListenerList;
private:
ListenerList listeners;
boost::mutex mutex;
public:
Logger();
~Logger();
Logger * write(const String &line);
};
Logger * Logger::write(const String &text) {
if(listeners.empty()) return this;
boost::unique_lock<boost::mutex> lock(mutex);
for(ListenerList::iterator i = listeners.begin(); i != listeners.end(); ++i) {
(*i)->write(text);
}
return this;
}
class FileLogListener : public LogListener {
std::ofstream stream;
public:
FileLogListener(const String &str) : stream(str.c_str(), std::ios::out | std::ios::app) { }
void write(const String &text) {
stream << text << std::endl;
}
};
现在假设(避免互斥):
Now suppose (avoiding mutexes):
//Thread 1
void func1() {
Logger * log = new Logger;
log->addListener("file.txt");
log->write("Thread 1 Test");
}
//Thread 2
void func2() {
Logger * log = new Logger;
log->addListener("file.txt");
log->write("Thread 2 test");
}
int main() {
boost::thread t1(&func1);
boost::thread t2(&func2);
t1.join();
t2.join();
return 0;
}
file.txt的变得一团糟。
"file.txt" becomes a mess.
编辑:目前,我正在读和多线程观看讲座更好地理解它。
Currently, I am reading and watching lectures on Multithreading to understand it better.
编辑:以上记录仪的工作原理
The above logger works.
在前进,结果谢谢
卡西姆Gasimzada
Thanks in advance,
Gasim Gasimzada
推荐答案
要么不写同一个文件,或者将连载写入(例如,通过使用锁)。
Either don't write to the same file, or serialise the writes (e.g. by using a lock).
这篇关于多线程日志帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!