1 // Copyright 2020 The Pigweed Authors
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
7 // https://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
17 #include "pw_assert/light.h"
18 #include "pw_chrono/system_clock.h"
19 #include "pw_chrono_freertos/system_clock_constants.h"
20 #include "pw_interrupt/context.h"
21 #include "pw_sync/mutex.h"
26 inline Mutex::Mutex() : native_type_() {
27 native_type_.handle = xSemaphoreCreateMutexStatic(&native_type_.buffer);
28 // This should never fail since the pointer provided was not null.
29 PW_DASSERT(native_type_.handle != nullptr);
32 inline Mutex::~Mutex() { vSemaphoreDelete(&native_type_); }
34 inline void Mutex::lock() {
35 PW_ASSERT(!interrupt::InInterruptContext());
36 #if INCLUDE_vTaskSuspend == 1 // This means portMAX_DELAY is indefinite.
37 const BaseType_t result = xSemaphoreTake(native_type_.handle, portMAX_DELAY);
38 PW_DASSERT(result == pdTRUE);
40 // In case we need to block for longer than the FreeRTOS delay can represent
41 // repeatedly hit take until success.
42 while (xSemaphoreTake(native_type_.handle,
43 chrono::freertos::kMaxTimeout.count()) == pdFALSE) {
45 #endif // INCLUDE_vTaskSuspend
48 inline bool Mutex::try_lock() {
49 PW_ASSERT(!interrupt::InInterruptContext());
50 return xSemaphoreTake(native_type_.handle, 0) == pdTRUE;
53 inline bool Mutex::try_lock_until(
54 chrono::SystemClock::time_point until_at_least) {
55 return try_lock_for(until_at_least - chrono::SystemClock::now());
58 inline void Mutex::unlock() {
59 PW_ASSERT(!interrupt::InInterruptContext());
60 // Unlocking only fails if it was not locked first.
61 PW_ASSERT(xSemaphoreGive(native_type_.handle) == pdTRUE);
64 inline Mutex::native_handle_type Mutex::native_handle() { return native_type_; }
66 } // namespace pw::sync