this_executor.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Copyright (C) 2014 Vicente Botet
  2. //
  3. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  4. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  5. #include <boost/config.hpp>
  6. #if ! defined BOOST_NO_CXX11_DECLTYPE
  7. #define BOOST_RESULT_OF_USE_DECLTYPE
  8. #endif
  9. #define BOOST_THREAD_VERSION 5
  10. #define BOOST_THREAD_USES_LOG_THREAD_ID
  11. #include <boost/thread/caller_context.hpp>
  12. #include <boost/thread/executors/basic_thread_pool.hpp>
  13. #include <boost/thread/executors/generic_executor_ref.hpp>
  14. #include <boost/smart_ptr/shared_ptr.hpp>
  15. #include <boost/smart_ptr/make_shared.hpp>
  16. #include <string>
  17. #include <iostream>
  18. #include <boost/thread/caller_context.hpp>
  19. struct current_executor_state_type {
  20. boost::shared_ptr<boost::generic_executor_ref> current_executor_ptr;
  21. template <class Executor>
  22. void set_current_executor(Executor& ex)
  23. {
  24. current_executor_ptr = boost::make_shared<boost::generic_executor_ref>(ex);
  25. }
  26. boost::generic_executor_ref current_executor()
  27. {
  28. if (current_executor_ptr)
  29. return *current_executor_ptr;
  30. else
  31. throw "";
  32. }
  33. };
  34. thread_local current_executor_state_type current_executor_state;
  35. boost::generic_executor_ref current_executor()
  36. {
  37. return current_executor_state.current_executor();
  38. }
  39. void p2()
  40. {
  41. std::cout << BOOST_CONTEXTOF << std::endl;
  42. boost::this_thread::sleep_for(boost::chrono::milliseconds(200));
  43. std::cout << BOOST_CONTEXTOF << std::endl;
  44. }
  45. void p1()
  46. {
  47. std::cout << BOOST_CONTEXTOF << std::endl;
  48. boost::this_thread::sleep_for(boost::chrono::milliseconds(200));
  49. current_executor().submit(&p2);
  50. boost::this_thread::sleep_for(boost::chrono::milliseconds(400));
  51. std::cout << BOOST_CONTEXTOF << std::endl;
  52. }
  53. int main()
  54. {
  55. std::cout << BOOST_CONTEXTOF << std::endl;
  56. boost::basic_thread_pool tp(4,
  57. // at_thread_entry
  58. [](boost::basic_thread_pool& pool)
  59. {
  60. current_executor_state.set_current_executor(pool);
  61. }
  62. );
  63. tp.submit(&p1);
  64. boost::this_thread::sleep_for(boost::chrono::seconds(5));
  65. std::cout << BOOST_CONTEXTOF << std::endl;
  66. return 1;
  67. }