我創建一個多線程的程序和多個線程可能需要調用一個全局函數併發日誌文件訪問/ 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)。 –