|
| 1 | +/* |
| 2 | + CoreMutex for the Raspberry Pi Pico RP2040 |
| 3 | +
|
| 4 | + Implements a deadlock-safe multicore mutex for sharing things like the |
| 5 | + USB or UARTs. |
| 6 | +
|
| 7 | + Copyright (c) 2021 Earle F. Philhower, III <[email protected]> |
| 8 | +
|
| 9 | + This library is free software; you can redistribute it and/or |
| 10 | + modify it under the terms of the GNU Lesser General Public |
| 11 | + License as published by the Free Software Foundation; either |
| 12 | + version 2.1 of the License, or (at your option) any later version. |
| 13 | +
|
| 14 | + This library is distributed in the hope that it will be useful, |
| 15 | + but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 16 | + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 17 | + Lesser General Public License for more details. |
| 18 | +
|
| 19 | + You should have received a copy of the GNU Lesser General Public |
| 20 | + License along with this library; if not, write to the Free Software |
| 21 | + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA |
| 22 | +*/ |
| 23 | + |
| 24 | +#include "Arduino.h" |
| 25 | +#include "CoreMutex.h" |
| 26 | + |
| 27 | +CoreMutex::CoreMutex(mutex_t *mutex, bool debugEnable) { |
| 28 | + _mutex = mutex; |
| 29 | + _acquired = false; |
| 30 | + if (__isFreeRTOS) { |
| 31 | + auto m = __get_freertos_mutex_for_ptr(mutex); |
| 32 | + __freertos_mutex_take(m); |
| 33 | + } else { |
| 34 | + uint32_t owner; |
| 35 | + if (!mutex_try_enter(_mutex, &owner)) { |
| 36 | + if (owner == get_core_num()) { // Deadlock! |
| 37 | + if (debugEnable) { |
| 38 | + DEBUGCORE("CoreMutex - Deadlock detected!\n"); |
| 39 | + } |
| 40 | + return; |
| 41 | + } |
| 42 | + mutex_enter_blocking(_mutex); |
| 43 | + } |
| 44 | + } |
| 45 | + _acquired = true; |
| 46 | +} |
| 47 | + |
| 48 | +CoreMutex::~CoreMutex() { |
| 49 | + if (_acquired) { |
| 50 | + if (__isFreeRTOS) { |
| 51 | + auto m = __get_freertos_mutex_for_ptr(_mutex); |
| 52 | + __freertos_mutex_give(m); |
| 53 | + } else { |
| 54 | + mutex_exit(_mutex); |
| 55 | + } |
| 56 | + } |
| 57 | +} |
0 commit comments