一个老项目需要获取错误信息,来记录日志. 没法用 callonce , 还得支持并发调用;
直接改用 InterlockedCompareExchange 来解决
InterlockedCompareExchange 在c11中可换成callonce 或者 使用 compare_exchange_strong 来实现
简化版:
class ErrorInfo{
public:
enum EnumRunState{ Running = 0, NotRun = 1} ;
static volatile long __atomicRunOnce;
public:
static void Init() {
if(NotRun == InterlockedCompareExchange(&ErrorInfo::__atomicRunOnce,EnumRunState::Running,EnumRunState::NotRun)){
// 只运行一次需要执行的代码放这
}
}
};
volatile long ErrorInfo::__atomicRunOnce = ErrorInfo::EnumRunState::NotRun;
// InterlockedCompareExchange 在c11中可换成callonce 或者 使用 compare_exchange_strong 来实现
完整版:
#ifndef ERRORINFO_H
#define ERRORINFO_H
#include <Windows.h>
#include <locale.h>
#include <TCHAR.H>
#include <sstream>
#include <string>
#include <iostream>