c++:写入多线程程序中的文件

c++: Writing to a file in multithreaded program

本文关键字:文件 程序 多线程 c++      更新时间:2023-10-16

所以我有多个线程通过调用 Log::write 方法写入同一个文件。

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 方法是否安全?

你的代码很浪费,不遵循C++习语。

从最后开始 :是的,write线程安全的,因为 win32CRITICAL_SECTION保护它免受并发修改。

虽然:

  1. 为什么每次都打开和关闭流? 这是非常浪费的事情。 在构造函数中打开流并将其保持打开状态。 析构函数将处理关闭流。

  2. 如果要使用 Win32 关键部分,至少要使其 RAII 安全。 创建一个类,该类包装对关键部分的引用,将其锁定在构造函数中并在析构函数中解锁。 这样,即使抛出异常 - 也可以保证锁将被解锁。

  3. CriticalSection的减速到底在哪里? 它应该是Log的成员。

  4. 你知道std::mutex吗?

  5. 为什么要按值传递字符串? 这是非常低效的。 然后通过常量引用传递。

  6. 您对某些变量 (file_path) 使用 snake_case 表示,而对其他变量 (CriticalSection) 使用大骆驼大小写。 使用相同的约定。

  7. str从来都不是字符串变量的好名称,文件流也不是日志。 是执行实际日志记录的事情。logger是一个更好的名字。在我的更正中,它只是命名为m_file_stream.

更正的代码:

class Log
{
private:
std::mutex m_lock;
std::ofstream m_file_stream;
std::string m_file_path;
public:
Log(const std::string& file_path);
void write(const std::string& log);
};
Log::Log(const std::string& file_path):
m_file_path(file_path)
{
m_file_stream.open(m_file_path.c_str());
if (!m_file_stream.is_open() || !m_file_stream.good())
{
//throw relevant exception.
}
}
void Log::write(const std::string& log)
{
std::lock_guard<std::mutex> lock(m_lock);
m_file_stream << log << 'n';
}