Skip to content

Instantly share code, notes, and snippets.

@KaiserKatze
Last active November 26, 2020 14:06
Show Gist options
  • Save KaiserKatze/74bec3ea9dc0bd6609e79beec3e976d4 to your computer and use it in GitHub Desktop.
Save KaiserKatze/74bec3ea9dc0bd6609e79beec3e976d4 to your computer and use it in GitHub Desktop.
[C++] Conccurrent ouput stream wrapper
#include <mutex>
#include <iostream>
#include <utility>
static std::mutex mtx_concurrent_stream;
struct concurrent_ostream
{
private:
std::ostream&& os;
public:
concurrent_ostream(std::ostream&& os)
: os{ std::move(os) }
{
}
template <typename... _Types>
concurrent_ostream& operator<<(_Types&&... _Values)
{
std::lock_guard<std::mutex> lk{ mtx_concurrent_stream };
os << std::forward<_Types...>(_Values...);
return *this;
}
operator bool() { return static_cast<bool>(os); }
};
struct concurrent_istream
{
private:
std::istream&& is;
public:
concurrent_istream(std::istream&& is)
: is{ std::move(is) }
{
}
template <typename _Type>
concurrent_istream& operator>>(_Type&& _Value)
{
std::lock_guard<std::mutex> lk{ mtx_concurrent_stream };
is >> std::forward<_Type>(_Value);
return *this;
}
operator bool() { return static_cast<bool>(is); }
};
static concurrent_ostream ccout{ std::move(std::cout) },
cclog{ std::move(std::clog) },
ccerr{ std::move(std::cerr) };
static concurrent_istream ccin{ std::move(std::cin) };
int main(int argc, char** argv)
{
ccout << "Hello world!\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment