如何在C++中安全正确的使用线程?

How to safely and properly use threads in C++?

我的应用程序有一个日志系统现在这就是我所做的:

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

namespace {  // Anonymous namespace instead of static functions.

std::mutex log_mutex;

void Background() {
    while(IsAlive){
        std::queue<std::string> log_records;
        {
            // Exchange data for minimizing lock time.
            std::unique_lock lock(log_mutex);
            logs.swap(log_records);
        }
        if (log_records.empty()) {
            Sleep(200);
            continue;
        }
        while(!log_records.empty()){
            ShowLog(log_records.front()); 
            log_records.pop();
        }
    }
}

void Log(std::string log){
    std::unique_lock lock(log_mutex);
    logs.push(std::move(log));
}

}