fork download
  1. #include <streambuf>
  2. #include <ios>
  3. #include <thread>
  4. #include <sstream>
  5.  
  6. class seppjs_thread_logger_streambuf : public std::streambuf
  7. {
  8. public:
  9. seppjs_thread_logger_streambuf(std::ios& in) : in(in), buf (in.rdbuf()), newline(true)
  10. {
  11. in.rdbuf(this);
  12. }
  13. ~seppjs_thread_logger_streambuf()
  14. {
  15. in.rdbuf(buf);
  16. }
  17. seppjs_thread_logger_streambuf(const seppjs_thread_logger_streambuf&) = delete;
  18. seppjs_thread_logger_streambuf& operator=(const seppjs_thread_logger_streambuf&) = delete;
  19.  
  20. private:
  21. std::ios& in;
  22. std::streambuf* buf;
  23. bool newline;
  24. protected:
  25. virtual int_type overflow(int_type c)
  26. {
  27. if(newline)
  28. {
  29. std::stringstream message;
  30. message << "Task " << std::this_thread::get_id() << ": ";
  31. buf->sputn(message.str().data(), message.str().size());
  32. newline = false;
  33. }
  34. if (traits_type::eq_int_type(c, traits_type::to_int_type('\n')))
  35. newline = true;
  36. buf->sputc(c);
  37. return c;
  38. }
  39. };
  40.  
  41.  
  42. // Beispielanwendung
  43. #include <iostream>
  44.  
  45. void function()
  46. {
  47. std::cout << "Blah\nBlupp\nBäh\n";
  48. }
  49.  
  50. int main()
  51. {
  52. seppjs_thread_logger_streambuf foo(std::cout);
  53. std::thread t1(function), t2(function);
  54.  
  55. t1.join();
  56. t2.join();
  57. }
  58.  
Success #stdin #stdout 0s 20880KB
stdin
Standard input is empty
stdout
Task 3066940224: Blah
Task 3066940224: Blupp
Task 3066940224: Bäh
Task 3075328832: Blah
Task 3075328832: Blupp
Task 3075328832: Bäh