BehaviorTree
Core Library to create and execute Behavior Trees
Loading...
Searching...
No Matches
callback_gate.h
1#pragma once
2
3#include <condition_variable>
4#include <memory>
5#include <mutex>
6
7namespace BT::details
8{
9
10/**
11 * @brief Synchronization gate used to coordinate callbacks with object teardown.
12 *
13 * Callbacks enter the gate with tryStart() and must signal completion when done
14 * (use Guard for RAII). During teardown, call close() to reject new callbacks
15 * and closeAndDrain() to block until the callbacks still running have completed.
16 */
17class CallbackGate
18{
19public:
20 using Ptr = std::shared_ptr<CallbackGate>;
21
22 /// RAII helper that signals the completion of a callback entered with tryStart()
23 class Guard
24 {
25 public:
26 explicit Guard(Ptr gate) : gate_(std::move(gate))
27 {}
28
29 Guard(const Guard&) = delete;
30 Guard& operator=(const Guard&) = delete;
31 Guard(Guard&&) = delete;
32 Guard& operator=(Guard&&) = delete;
33
34 ~Guard()
35 {
36 gate_->completed();
37 }
38
39 private:
40 Ptr gate_;
41 };
42
43 /// Returns false if the gate has been closed and the callback must not run.
44 bool tryStart()
45 {
46 const std::lock_guard lk(mutex_);
47 if(!accepting_callbacks_)
48 {
49 return false;
50 }
51 running_callbacks_++;
52 return true;
53 }
54
55 /// Reject new callbacks, without waiting for the running ones.
56 void close()
57 {
58 const std::lock_guard lk(mutex_);
59 accepting_callbacks_ = false;
60 }
61
62 /// Reject new callbacks and wait until callbacks already running have completed.
63 void closeAndDrain()
64 {
65 std::unique_lock lk(mutex_);
66 accepting_callbacks_ = false;
67 condition_variable_.wait(lk, [this] { return running_callbacks_ == 0; });
68 }
69
70private:
71 void completed()
72 {
73 const std::lock_guard lk(mutex_);
74 running_callbacks_--;
75 if(running_callbacks_ == 0 && !accepting_callbacks_)
76 {
77 condition_variable_.notify_all();
78 }
79 }
80
81 std::mutex mutex_;
82 std::condition_variable condition_variable_;
83 bool accepting_callbacks_ = true;
84 size_t running_callbacks_ = 0;
85};
86
87} // namespace BT::details
RAII helper that signals the completion of a callback entered with tryStart()
Definition: callback_gate.h:24
Synchronization gate used to coordinate callbacks with object teardown.
Definition: callback_gate.h:18
void close()
Reject new callbacks, without waiting for the running ones.
Definition: callback_gate.h:56
void closeAndDrain()
Reject new callbacks and wait until callbacks already running have completed.
Definition: callback_gate.h:63
bool tryStart()
Returns false if the gate has been closed and the callback must not run.
Definition: callback_gate.h:44
The SwitchNode is equivalent to a switch statement, where a certain branch (child) is executed accord...
Definition: basic_types.h:532
Definition: action_node.h:24