c++:写入多线程程序中的文件
c++: Writing to a file in multithreaded program
所以我有多个线程通过调用 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
保护它免受并发修改。
虽然:
-
为什么每次都打开和关闭流? 这是非常浪费的事情。 在构造函数中打开流并将其保持打开状态。 析构函数将处理关闭流。
-
如果要使用 Win32 关键部分,至少要使其 RAII 安全。 创建一个类,该类包装对关键部分的引用,将其锁定在构造函数中并在析构函数中解锁。 这样,即使抛出异常 - 也可以保证锁将被解锁。
-
CriticalSection
的减速到底在哪里? 它应该是Log
的成员。 -
你知道
std::mutex
吗? -
为什么要按值传递字符串? 这是非常低效的。 然后通过常量引用传递。
-
您对某些变量 (
file_path
) 使用 snake_case 表示,而对其他变量 (CriticalSection
) 使用大骆驼大小写。 使用相同的约定。 -
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';
}
相关文章:
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到
- 使用mongocxx驱动程序时包含头文件问题
- 使用VerQueryValue检索应用程序的文件描述
- 编译多文件C++程序
- Visual C 32位整数从文件到8位字符到文件 - 程序在某些整数上崩溃
- 文件程序不会停止显示垃圾值
- 简单的QT从文本文件程序中读取不编译
- 从文件 C++ 程序读取停止工作
- C++ - 需要有关如何正确设计多文件程序的建议
- C++文件 I/O - 程序挂起
- 简单的文件 I/O 程序C++
- 有一个简单的程序文件/程序文件(x86)指令的c++在windows
- 配置文件c++程序在perf
- 从同一文件夹读取文件(c++程序)
- 单文件程序的未定义虚函数表
- 无法用多文件程序创建SDL线程
- 我的第一个多文件C++程序不断给我错误消息
- 配置文件C++程序基于墙上的时钟时间与英特尔Vtune放大器
- c++复制文本文件程序使用头文件