【发布时间】:2021-08-16 09:08:41
【问题描述】:
我的应用程序有一个日志系统现在这就是我要做的:
static void Background() {
while(IsAlive){
while(!logs.empty()){
ShowLog(log.front());
log.pop();
}
while(logs.empty()){
Sleep(200);
}
}
}
static void Init(){
// Some Checks
Logger::backgroundThread = std::thread(Background);
backgroundThread.detach();
}
static void Log(std::string log){
logs.push(log);
}
static void ShowLog(std::string log){
// Actual implementation is bit complex but that does not involve threads so i guess it is irrelevant for this question
std::cout << log << std::endl;
}
这里是log 是std::queue<std::string>。
现在我不太确定这是否是一个好方法。
有没有更好的方法来实现这一点。
注意我使用的是 C++17
【问题讨论】:
-
至少您需要查看
std::mutex或无锁队列,以同时保护程序免受pushing 和popping 的影响。 -
while(logs.empty()){ Sleep(200); }- 使用std::condition_variable而不是这样的结构。 -
关注几分钟前问的this question。它非常相似,它得到的任何答案都将适用于您的案例。
-
为您提供很棒的日志库列表here,如果只是为了灵感。
-
不是线程安全,而是在
void Log中使用std::move(log)
标签: c++ multithreading parallel-processing thread-safety c++17