在C++ 11中同步整个类

Que*_*ueg 2 c++ synchronization mutex iostream c++11

看看这个简单的日志记录类(这里只介绍相关部分):

class Logger {
public:
    void log(string& msg){
        //lock for all instances
        cout << "[" << tag << "] " << msg;
        //unlock
    }
private:
     string tag;

};
Run Code Online (Sandbox Code Playgroud)

同步整个类(非实例)的最简单方法是什么,以便Logger(在不同的线程中)的单独实例cout按顺序写入(而不是一次性写入)?

Nik*_* C. 7

通常的方式,使用互斥量:

#include <mutex>

class Logger {
public:
    void log(string& msg)
    {
        // Lock for all instances
        std::lock_guard<std::mutex> lock(coutMutex);

        cout << "[" << tag << "] " << msg;

        // Unlocking happens automatically since the lock
        // gets destroyed here.
    }

private:
    string tag;
    static std::mutex coutMutex; // Don't forget to define this somewhere.
};
Run Code Online (Sandbox Code Playgroud)