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 */
16template <typename T>
17class LockedPtr
18{
19public:
20 LockedPtr() = default;
21
22 LockedPtr(T* obj, std::mutex* obj_mutex) : ref_(obj), mutex_(obj_mutex)
23 {
24 mutex_->lock();
25 }
26
27 ~LockedPtr()
28 {
29 if(mutex_ != nullptr)
30 {
31 mutex_->unlock();
32 }
33 }
34
35 LockedPtr(LockedPtr const&) = delete;
36 LockedPtr& operator=(LockedPtr const&) = delete;
37
38 LockedPtr(LockedPtr&& other) noexcept
39 {
40 std::swap(ref_, other.ref_);
41 std::swap(mutex_, other.mutex_);
42 }
43
44 LockedPtr& operator=(LockedPtr&& other) noexcept
45 {
46 std::swap(ref_, other.ref_);
47 std::swap(mutex_, other.mutex_);
48 return *this;
49 }
50
51 operator bool() const
52 {
53 return ref_ != nullptr;
54 }
55
56 void lock()
57 {
58 if(mutex_ != nullptr)
59 {
60 mutex_->lock();
61 }
62 }
63
64 void unlock()
65 {
66 if(mutex_ != nullptr)
67 {
68 mutex_->unlock();
69 }
70 }
71
72 const T* get() const
73 {
74 return ref_;
75 }
76
77 const T* operator->() const
78 {
79 return ref_;
80 }
81
82 T* operator->()
83 {
84 return ref_;
85 }
86
87 template <typename OtherT>
88 void assign(const OtherT& other)
89 {
90 if(ref_ == nullptr)
91 {
92 throw std::runtime_error("Empty LockedPtr reference");
93 }
94 else if constexpr(std::is_same_v<T, OtherT>)
95 {
96 *ref_ = other;
97 }
98 else if constexpr(std::is_same_v<BT::Any, OtherT>)
99 {
100 other->copyInto(*ref_);
101 }
102 else
103 {
104 *ref_ = T(other);
105 }
106 }
107
108private:
109 T* ref_ = nullptr;
110 std::mutex* mutex_ = nullptr;
111};
112
113} // 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:18
Definition: action_node.h:24