Xyris  0.5
RAII.hpp
Go to the documentation of this file.
1 /**
2  * @file RAII.hpp
3  * @author Keeton Feavel ([email protected])
4  * @brief Resource Acquisition Is Initialization mutex. Locks when constructed
5  * and unlocks when destructed.
6  * @version 0.1
7  * @date 2022-01-26
8  *
9  * @copyright Copyright the Xyris Contributors (c) 2022
10  *
11  */
12 #pragma once
13 
14 #include "Mutex.hpp"
15 
16 class RAIIMutex {
17 public:
18  /**
19  * @brief Construct a new RAIIMutex object that locks when
20  * constructed and unlocks when destructed.
21  *
22  * @param mutex Mutex to use for RAII (un)locking
23  *
24  */
25  RAIIMutex(Mutex& mutex)
26  : m_Mutex(mutex)
27  {
28  m_Mutex.lock();
29  }
30 
31  /**
32  * @brief Destroy the RAIIMutex object and unlock the mutex
33  *
34  */
36  {
37  m_Mutex.unlock();
38  }
39 
40 private:
42 };
43 
44 /**
45  * @brief Mutex protected region lambda function. Executed the provided
46  * function after locking the provided mutex. Unlocks before returning.
47  * Provided lambda function cannot return any value, but may return at
48  * any point safely.
49  *
50  * @tparam Function Lambda function template
51  * @param lockedWork Function to be executed in a safe manner
52  * @param mutex Mutex to lock before lambda execution
53  */
54 template<typename Function>
55 void lockedRegion(Function lockedWork, Mutex& mutex)
56 {
57  RAIIMutex raiiMutex(mutex);
58  lockedWork();
59 }
Mutex::unlock
bool unlock()
Release the mutex.
Definition: Mutex.cpp:38
RAIIMutex::m_Mutex
Mutex & m_Mutex
Definition: RAII.hpp:41
Mutex
Definition: Mutex.hpp:16
Mutex::lock
bool lock()
Aquire the mutex.
Definition: Mutex.cpp:20
lockedRegion
void lockedRegion(Function lockedWork, Mutex &mutex)
Mutex protected region lambda function. Executed the provided function after locking the provided mut...
Definition: RAII.hpp:55
RAIIMutex::RAIIMutex
RAIIMutex(Mutex &mutex)
Construct a new RAIIMutex object that locks when constructed and unlocks when destructed.
Definition: RAII.hpp:25
RAIIMutex
Definition: RAII.hpp:16
Mutex.hpp
RAIIMutex::~RAIIMutex
~RAIIMutex()
Destroy the RAIIMutex object and unlock the mutex.
Definition: RAII.hpp:35