我在课堂上保护我的线程函数CRITICAL_SECTION
并执行大量发送/接收套接字操作,一切正常,但如果线程正在写入日志文件,我就会遇到麻烦!
H
class ClassA
{
public:
ClassA();
~ClassA();
void run();
...
private:
CRITICAL_SECTION criticalSection;
LogFiles *m_logFiles;
...
};
cpp
ClassA::ClassA()
{
m_logFiles = new LogFiles();
InitializeCriticalSection(&criticalSection);
}
ClassA::~ClassA()
{
delete m_logFiles;
DeleteCriticalSection(&criticalSection);
}
void ClassA::run()
{
EnterCriticalSection(&criticalSection);
// do some stuff
m_logFiles->WriteToFile(message);
// do some stuff
m_logFiles->WriteToFile(message);
LeaveCriticalSection(&criticalSection);
}
日志文件不包含所有信息(仅来自例如 4 个线程中的 2 个的数据)或覆盖的行(2 个线程同时写入)!
所以我想我还必须保护 LogFiles 中的 WriteToFile 方法?!
感谢您的帮助和/或示例!