Last active
May 17, 2016 10:26
-
-
Save alecthomas/c038d0ce131325730ade to your computer and use it in GitHub Desktop.
Simple, type and thread safe C++11 console logging function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <mutex> | |
std::recursive_mutex log_lock; | |
// If you have ever tried using cerr/cout from multiple threads you may have experienced | |
// character interleaving. These functions avoid that. | |
template <typename A> | |
void log(const A &arg) { | |
log_lock.lock(); | |
std::cerr << arg << std::endl; | |
log_lock.unlock(); | |
} | |
template <typename A0, typename A1, typename ... Args> | |
void log(const A0 &a0, const A1 &a1, const Args & ... args) { | |
log_lock.lock(); | |
std::cerr << a0; | |
log(a1, args...); | |
log_lock.unlock(); | |
} | |
int main() { | |
const char *name = "bob"; | |
log("hello ", name); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment