packio
manual_strand.h
1 // This Source Code Form is subject to the terms of the Mozilla Public
2 // License, v. 2.0. If a copy of the MPL was not distributed with this
3 // file, You can obtain one at https://mozilla.org/MPL/2.0/.
4 
5 #ifndef PACKIO_MANUAL_STRAND_H
6 #define PACKIO_MANUAL_STRAND_H
7 
8 #include <queue>
9 
10 #include "config.h"
11 #include "movable_function.h"
12 
13 namespace packio {
14 namespace internal {
15 
16 template <typename Executor>
17 class manual_strand {
18 public:
19  using function_type = movable_function<void()>;
20 
21  explicit manual_strand(net::strand<Executor>& strand) : strand_{strand} {}
22 
23  void push(function_type function)
24  {
25  net::dispatch(strand_, [this, function = std::move(function)]() mutable {
26  queue_.push(std::move(function));
27 
28  if (!executing_) {
29  executing_ = true;
30  execute();
31  }
32  });
33  }
34 
35  void next()
36  {
37  net::dispatch(strand_, [this] { execute(); });
38  }
39 
40 private:
41  void execute()
42  {
43  if (queue_.empty()) {
44  executing_ = false;
45  return;
46  }
47 
48  auto function = std::move(queue_.front());
49  queue_.pop();
50  function();
51  }
52 
53  net::strand<Executor>& strand_;
54  std::queue<function_type> queue_;
55  bool executing_{false};
56 };
57 
58 } // internal
59 } // packio
60 
61 #endif // PACKIO_MANUAL_STRAND_H
The packio namespace.
Definition: arg.h:14