exchange.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright Arnaud Kapp, Oliver Kowalke 2016
  2. // Distributed under the Boost Software License, Version 1.0.
  3. // (See accompanying file LICENSE_1_0.txt or copy at
  4. // http://www.boost.org/LICENSE_1_0.txt)
  5. #include <iostream>
  6. #include <memory>
  7. #include <thread>
  8. #include <boost/asio.hpp>
  9. #include <boost/fiber/all.hpp>
  10. #include "round_robin.hpp"
  11. std::shared_ptr< boost::fibers::unbuffered_channel< int > > c;
  12. void foo() {
  13. auto io_ptr = std::make_shared< boost::asio::io_service >();
  14. boost::fibers::use_scheduling_algorithm< boost::fibers::asio::round_robin >( io_ptr);
  15. boost::fibers::fiber([io_ptr](){
  16. for ( int i = 0; i < 10; ++i) {
  17. std::cout << "push " << i << std::endl;
  18. c->push( i);
  19. }
  20. c->close();
  21. io_ptr->stop();
  22. }).detach();
  23. io_ptr->run();
  24. }
  25. void bar() {
  26. auto io_ptr = std::make_shared< boost::asio::io_service >();
  27. boost::fibers::use_scheduling_algorithm< boost::fibers::asio::round_robin >( io_ptr);
  28. boost::fibers::fiber([io_ptr](){
  29. try {
  30. for (;;) {
  31. int i = c->value_pop();
  32. std::cout << "pop " << i << std::endl;
  33. }
  34. } catch ( std::exception const& e) {
  35. std::cout << "exception: " << e.what() << std::endl;
  36. }
  37. io_ptr->stop();
  38. }).detach();
  39. io_ptr->run();
  40. }
  41. int main() {
  42. c = std::make_shared< boost::fibers::unbuffered_channel< int > >();
  43. std::thread t1( foo);
  44. std::thread t2( bar);
  45. t2.join();
  46. t1.join();
  47. std::cout << "done." << std::endl;
  48. return 0;
  49. }