fork(2) download
  1. #include <mutex>
  2. #include <iostream>
  3.  
  4.  
  5. class locked_stream
  6. {
  7. static std::mutex s_out_mutex;
  8.  
  9. std::unique_lock<std::mutex> lock_;
  10. std::ostream* stream_; // can't make this reference so we can move
  11.  
  12. public:
  13. locked_stream(std::ostream& stream)
  14. : lock_(s_out_mutex)
  15. , stream_(&stream)
  16. { }
  17.  
  18. locked_stream(locked_stream&& other)
  19. : lock_(std::move(other.lock_))
  20. , stream_(other.stream_)
  21. {
  22. other.stream_ = nullptr;
  23. }
  24.  
  25. friend locked_stream&& operator << (locked_stream&& s, std::ostream& (*arg)(std::ostream&))
  26. {
  27. (*s.stream_) << arg;
  28. return std::move(s);
  29. }
  30.  
  31. template <typename Arg>
  32. friend locked_stream&& operator << (locked_stream&& s, Arg&& arg)
  33. {
  34. (*s.stream_) << std::forward<Arg>(arg);
  35. return std::move(s);
  36. }
  37. };
  38.  
  39. std::mutex locked_stream::s_out_mutex{};
  40.  
  41. locked_stream locked_cout()
  42. {
  43. return locked_stream(std::cout);
  44. }
  45.  
  46. int main (int argc, char * argv[])
  47. {
  48. locked_cout() << "hello world: " << 1 << 3.14 << std::endl;
  49. return 0;
  50. }
Success #stdin #stdout 0s 3456KB
stdin
Standard input is empty
stdout
hello world: 13.14