not_interleaved.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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/externally_locked_stream.hpp>
  11. void use_cerr(boost::externally_locked_stream<std::ostream> &mcerr)
  12. {
  13. using namespace boost;
  14. chrono::steady_clock::time_point tf = chrono::steady_clock::now() + chrono::seconds(10);
  15. while (chrono::steady_clock::now() < tf)
  16. {
  17. mcerr << "logging data to cerr\n";
  18. this_thread::sleep_for(chrono::milliseconds(500));
  19. }
  20. }
  21. void use_cout(boost::externally_locked_stream<std::ostream> &mcout)
  22. {
  23. using namespace boost;
  24. chrono::steady_clock::time_point tf = chrono::steady_clock::now() + chrono::seconds(5);
  25. while (chrono::steady_clock::now() < tf)
  26. {
  27. mcout << "logging data to cout\n";
  28. this_thread::sleep_for(chrono::milliseconds(250));
  29. }
  30. }
  31. int main()
  32. {
  33. using namespace boost;
  34. recursive_mutex terminal_mutex;
  35. externally_locked_stream<std::ostream> mcerr(std::cerr, terminal_mutex);
  36. externally_locked_stream<std::ostream> mcout(std::cout, terminal_mutex);
  37. externally_locked_stream<std::istream> mcin(std::cin, terminal_mutex);
  38. scoped_thread<> t1(boost::thread(use_cerr, boost::ref(mcerr)));
  39. scoped_thread<> t2(boost::thread(use_cout, boost::ref(mcout)));
  40. this_thread::sleep_for(chrono::seconds(2));
  41. std::string nm;
  42. {
  43. strict_lock<recursive_mutex> lk(terminal_mutex);
  44. std::ostream & gcout = mcout.get(lk);
  45. //std::istream & gcin = mcin.get(lk);
  46. gcout << "Enter name: ";
  47. //gcin >> nm;
  48. }
  49. t1.join();
  50. t2.join();
  51. mcout << nm << '\n';
  52. return 0;
  53. }