|
| 1 | +/* |
| 2 | + * Copyright (c) 2018-present https://www.thecoderscorner.com (Nutricherry LTD). |
| 3 | + * This product is licensed under an Apache license, see the LICENSE file in the top-level directory. |
| 4 | + */ |
| 5 | + |
| 6 | +#ifndef TASKMANAGERIO_RENTRANTYIELDINGLOCK_H |
| 7 | +#define TASKMANAGERIO_RENTRANTYIELDINGLOCK_H |
| 8 | + |
| 9 | +#include "TaskManagerIO.h" |
| 10 | + |
| 11 | +/** |
| 12 | + * A lock that is intended only for use within tasks, if the lock is taken it will allow task manager to run using |
| 13 | + * it's yield for micros call until the lock becomes free. It is a spin lock, so it is safe to use with task manager. |
| 14 | + * Unless you want to use the spin behaviour in a specific way, prefer using with TaskSafeLock |
| 15 | + */ |
| 16 | +class ReentrantYieldingLock { |
| 17 | +private: |
| 18 | + tm_internal::TimerTaskAtomicPtr initiatingTask; |
| 19 | + tm_internal::TmAtomicBool locked; |
| 20 | + volatile uint8_t count; |
| 21 | + |
| 22 | +public: |
| 23 | + /** |
| 24 | + * Construct a reentrant yielding lock that is designed for use within task manager tasks |
| 25 | + */ |
| 26 | + ReentrantYieldingLock() { |
| 27 | + initiatingTask = nullptr; |
| 28 | + locked = false; |
| 29 | + count = 0; |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * Take the lock waiting the longest possible time for it to become available. |
| 34 | + */ |
| 35 | + void lock() { |
| 36 | + spinLock(0xFFFFFFFFUL); |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * Attempt to take the lock using a spin wait, it only returns true if the lock was taken. |
| 41 | + * @param micros micros to wait |
| 42 | + * @return true if the lock was taken, otherwise false |
| 43 | + */ |
| 44 | + bool spinLock(unsigned long micros); |
| 45 | + |
| 46 | + /** |
| 47 | + * Release the lock taken by spinlock or lock. DOES NOT check that the callee is correct so use carefully. |
| 48 | + */ |
| 49 | + void unlock(); |
| 50 | + |
| 51 | + uint8_t getLockCount() const { return count; } |
| 52 | + |
| 53 | + bool isLocked() const { return locked; } |
| 54 | +}; |
| 55 | + |
| 56 | +/** |
| 57 | + * A wrapper around the task manager locking facilities that allow you to lock within a block of code by putting |
| 58 | + * an instance on the stack, for example: |
| 59 | + * |
| 60 | + * ``` |
| 61 | + * ReentrantYieldingLock myLock; |
| 62 | + * void myFunctionToLock() { |
| 63 | + * TaskSafeLock(myLock); |
| 64 | + * // do some work that needs the lock here. lock will always be released. |
| 65 | + * } |
| 66 | + * ``` |
| 67 | + */ |
| 68 | +class TaskMgrLock { |
| 69 | +private: |
| 70 | + ReentrantYieldingLock& lock; |
| 71 | + |
| 72 | +public: |
| 73 | + TaskMgrLock(ReentrantYieldingLock& theLock) : lock(theLock) { |
| 74 | + lock.lock(); |
| 75 | + } |
| 76 | + |
| 77 | + ~TaskMgrLock() { |
| 78 | + lock.unlock(); |
| 79 | + } |
| 80 | +}; |
| 81 | + |
| 82 | +#endif //TASKMANAGERIO_RENTRANTYIELDINGLOCK_H |
0 commit comments