roo_threads
API Documentation for roo_threads
Loading...
Searching...
No Matches
mutex.cpp
Go to the documentation of this file.
2
3#ifdef ROO_THREADS_USE_FREERTOS
4
5#include <assert.h>
6
7#include "freertos/FreeRTOS.h"
8#include "freertos/semphr.h"
9#include "freertos/task.h"
11
12namespace roo_threads {
13namespace freertos {
14
15mutex::mutex() noexcept {
16#if !ROO_THREADS_FREERTOS_LAZY_INITIALIZE
17 xSemaphoreCreateMutexStatic(&mutex_);
18#endif
19}
20
21#if ROO_THREADS_FREERTOS_LAZY_INITIALIZE
22
23#if (defined(ESP32) || defined(ESP8266) || defined(ESP_PLATFORM)) && defined(configNUM_CORES)
24#if configNUM_CORES > 1
25static portMUX_TYPE s_mutex_init_lock = portMUX_INITIALIZER_UNLOCKED;
26#define mutexENTER_CRITICAL() portENTER_CRITICAL(&s_mutex_init_lock)
27#define mutexEXIT_CRITICAL() portEXIT_CRITICAL(&s_mutex_init_lock)
28#else
29#define mutexENTER_CRITICAL() vPortEnterCritical()
30#define mutexEXIT_CRITICAL() vPortExitCritical()
31#endif
32#else
33#define mutexENTER_CRITICAL() portENTER_CRITICAL()
34#define mutexEXIT_CRITICAL() portEXIT_CRITICAL()
35#endif
36
37void mutex::ensureInitialized() noexcept {
38 if (!initialized_) {
39 mutexENTER_CRITICAL();
40 if (!initialized_) {
41 xSemaphoreCreateMutexStatic(&mutex_);
42 initialized_ = true;
43 }
44 mutexEXIT_CRITICAL();
45 }
46}
47#else
48void mutex::ensureInitialized() noexcept {}
49#endif
50
51void mutex::lock() {
52 ensureInitialized();
53 if (xTaskGetCurrentTaskHandle() == nullptr) {
54 // Scheduler not yet running; no-op.
55 return;
56 }
57 xSemaphoreTake((SemaphoreHandle_t)&mutex_, portMAX_DELAY);
58}
59
60bool mutex::try_lock() {
61 ensureInitialized();
62 if (xTaskGetCurrentTaskHandle() == nullptr) {
63 // Scheduler not yet running; no-op.
64 return true;
65 }
66 return xSemaphoreTake((SemaphoreHandle_t)&mutex_, 0);
67}
68
69void mutex::unlock() {
70 ensureInitialized();
71 if (xTaskGetCurrentTaskHandle() == nullptr) {
72 // Scheduler not yet running; no-op.
73 return;
74 }
75 xSemaphoreGive((SemaphoreHandle_t)&mutex_);
76}
77
78namespace internal {
79
80void checkLockUnowned(const void* lock, bool owns) {
81 assert(lock != nullptr && !owns);
82}
83
84void checkLockOwned(bool owns) { assert(owns); }
85
86} // namespace internal
87
88} // namespace freertos
89} // namespace roo_threads
90
91#endif // ROO_THREADS_USE_FREERTOS