短版:寫一個同步的包裝,包裝std::cout
,然後使用同步cout
到寫。
龍版本:
#include <mutex>
template<typename T>
struct Synchronized {
explicit Synchronized(T& t_):t(t_) {}
template<typename Functor>
auto operator()(Functor&& f) const->decltype(f(t)) {
std::lock_guard<std::mutex> guard(myMutex);
return f(t);
}
// I could implement these, but I'm lazy:
Synchronized& operator=(Synchronized const&) = delete;
Synchronized& operator=(Synchronized &&) = delete;
Synchronized(Synchronized const&) = delete;
Synchronized(Synchronized &&) = delete;
private:
mutable T& t;
mutable std::mutex myMutex;
};
// in "sync_cout.h"
extern Synchronized<std::ostream> sync_cout;
// in "sync_cout.cpp"
Synchronized<std::ostream> sync_cout(std::cout);
// In "logger.h"
// #include "sync_cout.h"
class Logger {
public:
void log(string& msg){
sync_cout([&](std::ostream& os) {
os << "[" << tag << "] " << msg;
});
}
private:
string tag;
};
(從Herb被盜上述任何錯誤都是我自己的,不是香草的。)
對於性能優越,上面的鏈接還包括異步非阻塞包裝。
static/global mutex? – niXman 2013-02-18 08:21:47
應該添加一個互斥類型的'static'成員。 – Angew 2013-02-18 08:22:37
讓自己成爲一個同步的'std :: cout'。 – Xeo 2013-02-18 08:22:46