~aleteoryx/muditaos

ref: master muditaos/module-os/LockGuard.cpp -rw-r--r-- 924 bytes
2cd0e472 — Lefucjusz [BH-000] Update Harmony 2.10.0 changelog 2 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

#include "critical.hpp"
#include "LockGuard.hpp"
#include <macros.h>
#include <stdexcept>

namespace
{
    [[nodiscard]] bool isOSRunning()
    {
        return xTaskGetSchedulerState() == taskSCHEDULER_RUNNING;
    }
} // namespace

LockGuard::LockGuard(cpp_freertos::MutexStandard &mutex) : mutex(mutex)
{
    if (not isOSRunning()) {
        return;
    }
    if (isIRQ()) {
        savedInterruptStatus = cpp_freertos::CriticalSection::EnterFromISR();
    }
    else if (!mutex.Lock()) {
        throw std::runtime_error("LockGuard failed to lock mutex");
    }
}

LockGuard::~LockGuard()
{
    if (not isOSRunning()) {
        return;
    }
    if (isIRQ()) {
        cpp_freertos::CriticalSection::ExitFromISR(savedInterruptStatus);
    }
    else {
        mutex.Unlock();
    }
}