libqi-api  2.8.7.4
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
futuregroup.hpp
Go to the documentation of this file.
1 #pragma once
2 /*
3 ** Copyright (C) 2014 Aldebaran Robotics
4 ** See COPYING for the license
5 */
6 #include <boost/container/flat_map.hpp>
7 #include <boost/thread/synchronized_value.hpp>
8 #include <qi/future.hpp>
9 #include <qi/trackable.hpp>
10 
11 namespace qi
12 {
21  : boost::noncopyable
22  , public qi::Trackable<ScopedFutureGroup>
23  {
24  public:
28  {
29  destroy();
30  cancelAll();
31  }
32 
39  template< class T >
40  void add(Future<T> future)
41  {
42  _futureCancelList->emplace(future.uniqueId(), [future]() mutable { future.cancel(); });
43  future.then(qi::track( [this](Future<T> f){ onFutureFinished(f); }, this ));
44  }
45 
48  void cancelAll()
49  {
50  FutureCancelList cancelList;
51  {
52  auto synched_futureCancelList = _futureCancelList.synchronize();
53  swap(cancelList, *synched_futureCancelList);
54  }
55  for (auto& slot : cancelList)
56  {
57  try
58  {
59  slot.second();
60  }
61  catch (std::exception& ex)
62  {
63  qiLogWarning("qi.scopedfuturegroup") << "Failed to cancel scoped future: " << ex.what();
64  }
65  catch (...)
66  {
67  qiLogWarning("qi.scopedfuturegroup") << "Failed to cancel scoped future: unknown error.";
68  }
69 
70  }
71  }
72 
74  bool empty() const
75  {
76  return _futureCancelList->empty();
77  }
78 
80  size_t size() const
81  {
82  return _futureCancelList->size();
83  }
84 
85  private:
86 
87  using FutureCancelList = boost::container::flat_map< FutureUniqueId, boost::function<void()>>;
88  boost::synchronized_value<FutureCancelList> _futureCancelList;
89 
90  template<class T>
91  void onFutureFinished(Future<T> future)
92  {
93  _futureCancelList->erase(future.uniqueId());
94  }
95  };
96 }
auto track(F &&f, T &&toTrack) -> decltype(trackWithFallback(detail::throwPointerLockException, std::forward< F >(f), std::forward< T >(toTrack)))
Definition: trackable.hxx:420
size_t size() const
Definition: futuregroup.hpp:80
#define qiLogWarning(...)
Log in warning mode.
Definition: log.hpp:109
auto then(FutureCallbackType type, F &&func) -> Future< typename std::result_of< F(Future< T >)>::type >
Execute a callback when the future is finished.
Definition: future_fwd.hpp:453
void swap(::qi::AnyFunction &a,::qi::AnyFunction &b)
Definition: anyfunction.hxx:92
void cancel()
Definition: future_fwd.hpp:383
void add(Future< T > future)
Definition: futuregroup.hpp:40
Object tracking by blocking destruction while shared pointers are present.
Definition: trackable.hpp:45
FutureUniqueId uniqueId() const
Definition: future_fwd.hpp:217
bool empty() const
Definition: futuregroup.hpp:74