Skip to content

Instantly share code, notes, and snippets.

@yohhoy
Last active November 8, 2015 06:01
Show Gist options
  • Save yohhoy/1765fec3fb67c0c55a50 to your computer and use it in GitHub Desktop.
Save yohhoy/1765fec3fb67c0c55a50 to your computer and use it in GitHub Desktop.
multithread-safe alternative cout/wcout stream (line outputter)
/*
* mt_cline.hpp - multithread-safe alternative cout/wcout stream (line outputter)
*
* (C) Copyright yohhoy 2015.
* Distributed under the Boost Software License, Version 1.0.
* (See copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#include <iostream>
#include <mutex>
#include <string>
#include <utility>
template <typename charT, typename Trait=std::char_traits<charT>>
class mt_lineout {
using streamT = std::basic_ostream<charT, Trait>;
static std::mutex& guard() {
static std::mutex lineout_guard;
return lineout_guard;
}
streamT& os_;
public:
explicit mt_lineout(streamT& os) : os_(os) {
guard().lock();
}
~mt_lineout() {
std::endl(os_);
guard().unlock();
}
mt_lineout(const mt_lineout&) = delete;
mt_lineout& operator=(const mt_lineout&) = delete;
mt_lineout(mt_lineout&&) = default;
mt_lineout& operator=(mt_lineout&) = default;
template <typename U>
mt_lineout& operator<<(U&& u) {
os_ << std::forward<U>(u);
return *this;
}
// feed std::flush/endl/ends
mt_lineout& operator<<(streamT& (&)(streamT&)) { return *this; }
};
inline mt_lineout<char> cline()
{ return mt_lineout<char>(std::cout); }
inline mt_lineout<wchar_t> wcline()
{ return mt_lineout<wchar_t>(std::wcout); }
@yohhoy
Copy link
Author

yohhoy commented Nov 8, 2015

When you want to output "line by line" under multi-threaded code,

cline() << "Hello, world: " << 42 << " pi=" << 3.14;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment