L4Re Operating System Framework
Interface and Usage Documentation
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
lock_guard.h
Go to the documentation of this file.
1// vim:set ft=cpp: -*- Mode: C++ -*-
2/*
3 * Copyright (C) 2025 Kernkonzept GmbH.
4 * Author(s): Martin Decky <martin.decky@kernkonzept.com>
5 *
6 * License: see LICENSE.spdx (in this directory or the directories above)
7 */
8
14#pragma once
15
16#include <pthread.h>
17#include <stdlib.h>
18
19namespace L4 {
20
45{
46public:
47 Lock_guard() = delete;
48 Lock_guard(const Lock_guard &) = delete;
49 Lock_guard &operator=(const Lock_guard &) = delete;
50
59 explicit Lock_guard(pthread_mutex_t &lock) : _lock(&lock)
60 {
61 _status = pthread_mutex_lock(_lock);
62 }
63
71 Lock_guard(Lock_guard &&guard) : _lock(guard._lock), _status(guard._status)
72 {
73 guard.release();
74 }
75
91 {
92 // Unlock the currently associated mutex (if any).
93 reset();
94
95 // Move the state from the other guard.
96 _lock = guard._lock;
97 _status = guard._status;
98
99 // Release the mutex from the other guard.
100 guard.release();
101
102 return *this;
103 }
104
110 int status() const
111 {
112 return _status;
113 }
114
127 {
128 reset();
129 }
130
131private:
137 void release()
138 {
139 _lock = nullptr;
140 }
141
150 void reset()
151 {
152 // No mutex might be associated with this lock guard only if the mutex has
153 // been moved to a different lock guard.
154 if (_lock)
155 {
156 _status = pthread_mutex_unlock(_lock);
157 release();
158 }
159 }
160
161 pthread_mutex_t *_lock;
162 int _status;
163};
164
165} // namespace L4
Basic lock guard implementation that prevents forgotten unlocks on exit paths from a method or a bloc...
Definition lock_guard.h:45
Lock_guard(Lock_guard &&guard)
Move constructor from other lock guard.
Definition lock_guard.h:71
Lock_guard(pthread_mutex_t &lock)
Construct the lock guard and lock the associated mutex.
Definition lock_guard.h:59
~Lock_guard()
Lock guard destructor.
Definition lock_guard.h:126
Lock_guard & operator=(Lock_guard &&guard)
Move assignment from other lock guard.
Definition lock_guard.h:90
int status() const
Return last lock/unlock operation error status.
Definition lock_guard.h:110
L4 low-level kernel interface.