gpt4 book ai didi

c++ - C/C++ 中的并发日志文件访问

转载 作者:太空宇宙 更新时间:2023-11-04 05:10:38 25 4
gpt4 key购买 nike

我正在创建一个多线程程序,多个线程可能需要调用一个全局函数

writeLog(const char* pMsg);

并且 writeLog 将实现类似 tihs 的东西:

void writeLog(const char* pMsg)
{
CRITICAL_SECTION cs;

// initialize critical section
...

EnterCriticalSection(&cs);

// g_pLogFilePath is a global variable.
FILE *file;
if (0!=fopen_s(&file, g_pLogFilePath, "r+"))
return;

fprintf(file, pMsg);

fclose(file):
LeaveCriticalSection(&cs);
}

我的问题是:

1) is it the best way to do concurrent logging? i.e., using critical section.

2) since I will write log in many places in the threads,
and since each log writing will involve open/close file,
does the io will impact the performance significantly?

谢谢!

最佳答案

进行并发日志记录的最佳方法是使用 existing log library for C++ 之一.它们具有许多您可能会喜欢使用的特性(不同的附加程序、格式、并发性等)。

如果您仍然想拥有自己的解决方案,您可能会有这样的事情:初始化一次并保持状态(文件处理程序和互斥锁)的简单单例

class Log
{
public:

// Singleton
static Log & getLog()
{
static Log theLog;
return theLog;
}

void log(const std::string & message)
{
// synchronous writing here
}
private:
// Hidden ctor
Log()
{
// open file ONCE here
}

// Synchronisation primitive - instance variable
// CRITICAL_SECTION or Boost mutex (preferable)
CRITICAL_SECTION cs_;

// File handler: FILE * or std::ofstream
FILE * handler_;
};

关于c++ - C/C++ 中的并发日志文件访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12362875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com