test_9319.cpp 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright (C) 2013 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. // futtest.cpp
  6. #include <iostream>
  7. #define BOOST_THREAD_VERSION 4
  8. #include <boost/thread/future.hpp>
  9. #include <boost/thread/thread.hpp>
  10. #include <boost/bind.hpp>
  11. #include <boost/chrono.hpp>
  12. #include <boost/shared_ptr.hpp>
  13. #include <boost/scoped_ptr.hpp>
  14. typedef boost::shared_ptr< boost::promise<int> > IntPromise;
  15. void foo(IntPromise p)
  16. {
  17. std::cout << "foo" << std::endl;
  18. p->set_value(123); // This line locks the future's mutex, then calls the continuation with the mutex already locked.
  19. }
  20. void bar(boost::future<int> fooResult)
  21. {
  22. try {
  23. std::cout << "bar" << std::endl;
  24. int i = fooResult.get(); // Code hangs on this line (Due to future already being locked by the set_value call)
  25. std::cout << "i: " << i << std::endl;
  26. } catch(...) {
  27. std::cout << __FILE__ << ":" << __LINE__ << std::endl;
  28. }
  29. }
  30. int main()
  31. {
  32. std::cout << __FILE__ << ":" << __LINE__ << std::endl;
  33. try {
  34. IntPromise p(new boost::promise<int>());
  35. boost::thread t(boost::bind(foo, p));
  36. boost::future<int> f1 = p->get_future();
  37. f1.then(boost::launch::deferred, &bar);
  38. t.join();
  39. } catch(...) {
  40. return 1;
  41. }
  42. std::cout << __FILE__ << ":" << __LINE__ << std::endl;
  43. try {
  44. IntPromise p(new boost::promise<int>());
  45. boost::thread t(boost::bind(foo, p));
  46. boost::future<int> f1 = p->get_future();
  47. f1.then(boost::launch::async, &bar);
  48. t.join();
  49. } catch(...) {
  50. return 2;
  51. }
  52. std::cout << __FILE__ << ":" << __LINE__ << std::endl;
  53. }