Boboter
Loading...
Searching...
No Matches
protected_struct.h
Go to the documentation of this file.
1
7
8#pragma once
9
10#include <freertos/FreeRTOS.h>
12#include "lib/logger/logger.h"
13
42template <typename struct_type>
44private:
45 static constexpr const char* TAG = "protected_struct";
46
47 struct_type data;
48 mutable SemaphoreHandle_t mutex;
49
50 class mutex_lock {
51 public:
52 protected_struct* parent;
53
54 explicit mutex_lock(const protected_struct* parent) :
55 parent(const_cast<protected_struct*>(parent))
56 {
57 if (xSemaphoreGetMutexHolder(parent->mutex) == xTaskGetCurrentTaskHandle()) {
58 LOGE("Mutex deadlock detected, aborting");
60 }
61
62 xSemaphoreTake(parent->mutex, portMAX_DELAY);
63 }
64
65 ~mutex_lock() {
66 unlock();
67 }
68
72 void unlock() {
73 if (parent != nullptr) {
74 xSemaphoreGive(parent->mutex);
75 parent = nullptr;
76 }
77 }
78
79 struct_type* operator->() {
80 return parent != nullptr ? &parent->data : nullptr;
81 }
82
83 operator struct_type&() {
84 return parent->data;
85 }
86 };
87
88public:
89 explicit protected_struct() : mutex(xSemaphoreCreateMutex()) {
90 if (mutex == nullptr) {
91 LOGE("Mutex creation failed");
93 }
94 }
96 if (mutex != nullptr) {
97 vSemaphoreDelete(mutex);
98 }
99 }
100
103
110 mutex_lock operator->() const {
111 return mutex_lock(this);
112 }
113
119 mutex_lock lock() const {
120 return mutex_lock(this);
121 }
122};
protected_struct(const protected_struct &)=delete
mutex_lock operator->() const
Overload of the get value from dereferenced pointer operator to make it possible to get a value using...
Definition protected_struct.h:110
protected_struct & operator=(const protected_struct &)=delete
protected_struct()
Definition protected_struct.h:89
~protected_struct()
Definition protected_struct.h:95
mutex_lock lock() const
Locks the struct and holds the mutex for the returned object's scope.
Definition protected_struct.h:119
void halt_execution()
Definition halt_execution.h:13
#define LOGE(format,...)
Macro for error logging.
Definition logger.h:133