not_interleaved2.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // (C) Copyright 2012 Howard Hinnant
  2. // (C) Copyright 2012 Vicente Botet
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. // adapted from the example given by Howard Hinnant in
  7. #define BOOST_THREAD_VERSION 4
  8. #include <iostream>
  9. #include <boost/thread/scoped_thread.hpp>
  10. #include <boost/thread/ostream_buffer.hpp>
  11. void use_cerr()
  12. {
  13. using namespace boost;
  14. chrono::steady_clock::time_point tf = chrono::steady_clock::now() + chrono::seconds(5);
  15. int i = 0;
  16. while (chrono::steady_clock::now() < tf)
  17. {
  18. ostream_buffer<std::ostream> mcerr(std::cerr);
  19. mcerr.stream() << "logging data to cerr " << i++ << "\n";
  20. this_thread::sleep_for(chrono::milliseconds(250));
  21. }
  22. }
  23. void use_cout()
  24. {
  25. using namespace boost;
  26. chrono::steady_clock::time_point tf = chrono::steady_clock::now() + chrono::seconds(5);
  27. int i = 0;
  28. while (chrono::steady_clock::now() < tf)
  29. {
  30. ostream_buffer<std::ostream> mcout(std::cout);
  31. mcout.stream() << "logging data to cout " << i++ << "\n";
  32. this_thread::sleep_for(chrono::milliseconds(500));
  33. }
  34. }
  35. int main()
  36. {
  37. using namespace boost;
  38. scoped_thread<> t1(&use_cerr);
  39. scoped_thread<> t2(&use_cout);
  40. this_thread::sleep_for(chrono::seconds(2));
  41. std::string nm = "he, he\n";
  42. {
  43. ostream_buffer<std::ostream> mcout(std::cout);
  44. mcout.stream() << "Enter name: \n";
  45. }
  46. t1.join();
  47. t2.join();
  48. {
  49. ostream_buffer<std::ostream> mcout(std::cout);
  50. mcout.stream() << nm;
  51. }
  52. return 0;
  53. }