BehaviorTree
Core Library to create and execute Behavior Trees
Loading...
Searching...
No Matches
locked_reference.hpp
1#pragma once
2
3#include "behaviortree_cpp/utils/safe_any.hpp"
4
5#include <mutex>
6
7namespace BT
8{
9/**
10 * @brief The LockedPtr class is used to share a pointer to an object
11 * and a mutex that protects the read/write access to that object.
12 *
13 * As long as the object remains in scope, the mutex is locked, therefore
14 * you must destroy this instance as soon as the pointer was used.
15 *
16 * LockedPtr does not own the object it points to: the owner is only expected
17 * to keep it alive while the mutex is locked. In particular, the pointer must
18 * not be considered valid after calling unlock().
19 */
20template <typename T>
21class LockedPtr
22{
23public:
24 LockedPtr() = default;
25
26 LockedPtr(T* obj, std::mutex* obj_mutex) : ref_(obj), mutex_(obj_mutex)
27 {
28 mutex_->lock();
29 }
30
31 ~LockedPtr()
32 {
33 if(mutex_ != nullptr)
34 {
35 mutex_->unlock();
36 }
37 }
38
39 LockedPtr(LockedPtr const&) = delete;
40 LockedPtr& operator=(LockedPtr const&) = delete;
41
42 LockedPtr(LockedPtr&& other) noexcept
43 {
44 std::swap(ref_, other.ref_);
45 std::swap(mutex_, other.mutex_);
46 }
47
48 LockedPtr& operator=(LockedPtr&& other) noexcept
49 {
50 std::swap(ref_, other.ref_);
51 std::swap(mutex_, other.mutex_);
52 return *this;
53 }
54
55 operator bool() const
56 {
57 return ref_ != nullptr;
58 }
59
60 void lock()
61 {
62 if(mutex_ != nullptr)
63 {
64 mutex_->lock();
65 }
66 }
67
68 void unlock()
69 {
70 if(mutex_ != nullptr)
71 {
72 mutex_->unlock();
73 }
74 }
75
76 const T* get() const
77 {
78 return ref_;
79 }
80
81 const T* operator->() const
82 {
83 return ref_;
84 }
85
86 T* operator->()
87 {
88 return ref_;
89 }
90
91 template <typename OtherT>
92 void assign(const OtherT& other)
93 {
94 if(ref_ == nullptr)
95 {
96 throw std::runtime_error("Empty LockedPtr reference");
97 }
98 else if constexpr(std::is_same_v<T, OtherT>)
99 {
100 *ref_ = other;
101 }
102 else if constexpr(std::is_same_v<BT::Any, OtherT>)
103 {
104 other->copyInto(*ref_);
105 }
106 else
107 {
108 *ref_ = T(other);
109 }
110 }
111
112private:
113 T* ref_ = nullptr;
114 std::mutex* mutex_ = nullptr;
115};
116
117} // namespace BT
The LockedPtr class is used to share a pointer to an object and a mutex that protects the read/write ...
Definition: locked_reference.hpp:22
Definition: action_node.h:24