【发布时间】:2012-09-11 04:41:25
【问题描述】:
我正在创建一个多线程程序,多个线程可能需要调用一个全局函数
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时都会创建一个新的临界区(并在返回时泄漏它),所以它不是一个临界区全部。 -
临界区对象必须是全局的,see MSDN。
标签: c++ c multithreading winapi concurrency