Stride Reference Manual  1.0
async.h
Go to the documentation of this file.
1 #pragma once
2 
3 #include <future>
4 #include <vector>
5 #include <mutex>
6 #include <condition_variable>
7 
8 namespace stride {
9 namespace util {
10 
11 using namespace std;
12 
13 // partly based on http://stackoverflow.com/a/14921115/2678118
14 // Implements a simple boolean flag
15 class Flag {
16 public:
17  inline bool isSet() const {
18  lock_guard<mutex> lock(m_mut);
19  return m_flag;
20  }
21 
22  inline void set() {
23  {
24  lock_guard<mutex> lock(m_mut);
25  m_flag = true;
26  }
27  m_cv.notify_all();
28  }
29 
30  inline void reset() {
31  {
32  lock_guard<mutex> lock(m_mut);
33  m_flag = false;
34  }
35  m_cv.notify_all();
36  }
37 
38  inline void wait() const {
39  unique_lock<mutex> lock(m_mut);
40  if (m_flag) return;
41  m_cv.wait(lock, [this] { return m_flag; });
42  }
43 
44 private:
45  mutable mutex m_mut;
46  mutable condition_variable m_cv;
47  bool m_flag = false;
48 };
49 
50 
51 template<typename T>
52 vector<T> future_pool(vector<future<T>>& futures) {
53  vector<T> results;
54  mutex results_lock;
55  Flag all_done;
56 
57  for (auto& f: futures) {
58  async(std::launch::async, [&]() {
59  T res = f.get();
60  {
61  lock_guard<mutex> lock(results_lock);
62  results.push_back(res);
63  if (results.size() == futures.size())
64  all_done.set();
65  }
66  });
67  }
68 
69  all_done.wait();
70  return results;
71 }
72 
73 }
74 }
vector< T > future_pool(vector< future< T >> &futures)
Definition: async.h:52
void wait() const
Definition: async.h:38
Time Dependent Person DataType.
Definition: NoBehaviour.h:17
void set()
Definition: async.h:22
condition_variable m_cv
Definition: async.h:46
STL namespace.
void reset()
Definition: async.h:30
bool isSet() const
Definition: async.h:17