我创建一个多线程的程序和多个线程可能需要调用一个全局函数并发日志文件访问/ C++
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?
谢谢!
如果'cs'是一个局部变量,那么每次输入'writeLog'(当你返回时都会泄漏它),你就会创建一个新的临界区,所以它根本不是关键部分。 –
临界区对象必须是全局的,[见MSDN](http://msdn.microsoft.com/en-us/library/windows/desktop/ms686908%28v=vs.85%29.aspx)。 –