ME507 Utility Library  0.2.1
Mechatronics Course Support Software for ARM/Arduino/FreeRTOS
mutex.h
Go to the documentation of this file.
1 /** @file mutex.h
2  * This file contains C++ code which makes it easier to use semaphores such
3  * as mutexes (mutices?) to coordinate some actions between tasks.
4  *
5  * @author JR Ridgely
6  * @date 2020-Nov-16 Original file
7  */
8 
9 #include <Arduino.h>
10 #include <FreeRTOS.h>
11 
12 
13 /** @brief Class which implements a mutex which can guard a resource.
14  * @details A mutex (short for MUTual EXclusion) is used to ensure that two
15  * tasks don't use a resource at the same time. This is one method
16  * which can be used to prevent data corruption due to task
17  * switching. This class doesn't add functionality to the FreeRTOS
18  * mutex; it just simplifies the programming interface.
19  */
20 class Mutex
21 {
22 protected:
23  SemaphoreHandle_t handle; ///< Handle to the FreeRTOS mutex being used
24  TickType_t timeout; ///< How many RTOS ticks to wait for the mutex
25 
26 public:
27  /** @brief Create a mutex and save a handle to it.
28  * @details A mutex @b must @b not @b be @b used within an interrupt
29  * service routine; there are ways to use queues to accomplish
30  * the same goal. See the FreeRTOS documentation for details.
31  * @param timeout The number of RTOS ticks to wait for the mutex to
32  * become available if another task has it (default
33  * @c portMAX_DELAY which means wait forever)
34  */
35  Mutex (TickType_t timeout = portMAX_DELAY)
36  {
37  handle = xSemaphoreCreateMutex ();
38  this->timeout = timeout;
39  }
40 
41  /** @brief Take the mutex, preventing other tasks from using whatever
42  * resource the mutex protects.
43  * @returns @c true if the mutex was taken or @c false if we timed out
44  */
45  bool take (void)
46  {
47  portBASE_TYPE result = xSemaphoreTake (handle, timeout);
48 
49  return (result == pdTRUE);
50  }
51 
52  /** @brief Give back the mutex, allowing other tasks to access the
53  * resource protected by the mutex.
54  */
55  void give (void)
56  {
57  xSemaphoreGive (handle);
58  }
59 };
60 
61 
Mutex::timeout
TickType_t timeout
How many RTOS ticks to wait for the mutex.
Definition: mutex.h:24
Mutex::take
bool take(void)
Take the mutex, preventing other tasks from using whatever resource the mutex protects.
Definition: mutex.h:45
Mutex::Mutex
Mutex(TickType_t timeout=portMAX_DELAY)
Create a mutex and save a handle to it.
Definition: mutex.h:35
Mutex::give
void give(void)
Give back the mutex, allowing other tasks to access the resource protected by the mutex.
Definition: mutex.h:55
Mutex
Class which implements a mutex which can guard a resource.
Definition: mutex.h:20
Mutex::handle
SemaphoreHandle_t handle
Handle to the FreeRTOS mutex being used.
Definition: mutex.h:23