Loading...
Searching...
No Matches
lock_guard.h
Go to the documentation of this file.
// vim:set ft=cpp: -*- Mode: C++ -*-
/*
* Copyright (C) 2025 Kernkonzept GmbH.
* Author(s): Martin Decky <martin.decky@kernkonzept.com>
*
* License: see LICENSE.spdx (in this directory or the directories above)
*/
#pragma once
#include <pthread.h>
#include <stdlib.h>
namespace L4 {
class Lock_guard
{
public:
Lock_guard() = delete;
Lock_guard(const Lock_guard &) = delete;
Lock_guard &operator=(const Lock_guard &) = delete;
explicit Lock_guard(pthread_mutex_t &lock) : _lock(&lock)
{
_status = pthread_mutex_lock(_lock);
}
Lock_guard(Lock_guard &&guard) : _lock(guard._lock), _status(guard._status)
{
guard.release();
}
Lock_guard &operator=(Lock_guard &&guard)
{
// Unlock the currently associated mutex (if any).
reset();
// Move the state from the other guard.
_lock = guard._lock;
_status = guard._status;
// Release the mutex from the other guard.
guard.release();
return *this;
}
int status() const
{
return _status;
}
~Lock_guard()
{
reset();
}
private:
void release()
{
_lock = nullptr;
}
void reset()
{
// No mutex might be associated with this lock guard only if the mutex has
// been moved to a different lock guard.
if (_lock)
{
_status = pthread_mutex_unlock(_lock);
release();
}
}
pthread_mutex_t *_lock;
int _status;
};
} // namespace L4
L4::Lock_guard::Lock_guard
Lock_guard(Lock_guard &&guard)
Move constructor from other lock guard.
Definition lock_guard.h:71
L4::Lock_guard::Lock_guard
Lock_guard(pthread_mutex_t &lock)
Construct the lock guard and lock the associated mutex.
Definition lock_guard.h:59
L4::Lock_guard::~Lock_guard
~Lock_guard()
Lock guard destructor.
Definition lock_guard.h:126
L4::Lock_guard::operator=
Lock_guard & operator=(Lock_guard &&guard)
Move assignment from other lock guard.
Definition lock_guard.h:90
L4::Lock_guard::status
int status() const
Return last lock/unlock operation error status.
Definition lock_guard.h:110
L4
L4 low-level kernel interface.
Definition l4sys-l4f-groups.dox:50