Skip to content

Instantly share code, notes, and snippets.

@alecthomas
Last active May 17, 2016 10:26
Show Gist options
  • Save alecthomas/c038d0ce131325730ade to your computer and use it in GitHub Desktop.
Save alecthomas/c038d0ce131325730ade to your computer and use it in GitHub Desktop.
Simple, type and thread safe C++11 console logging function
#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