所以我有多个线程通过调用Log :: write方法写入同一个文件。C++:在多线程程序中写入文件
class Log
{
private:
ofstream log;
string file_path;
public:
Log(string);
void write(string);
};
Log::Log(string _file_path)
{
file_path=_file_path;
}
void Log::write(string str)
{
EnterCriticalSection(&CriticalSection);
log.open(file_path.c_str(),std::ofstream::app);
log<<str+'\n';
log.close();
LeaveCriticalSection(&CriticalSection);
}
线程是否会同时调用同一个对象的Log :: write方法是否安全?
是。考虑使用RAII锁定/解锁临界区以使其异常安全。考虑使用C++标准锁定。考虑使用单独的日志记录线程和消息队列来缩小锁定瓶颈。注意打开文件(在MS Windows下)是一个非常昂贵的操作 - 考虑将日志记录类更改为单例,并且只打开一次文件。 –
考虑使用第三方日志记录库 – ZivS