Zephyr C++ Toolkit
Loading...
Searching...
No Matches
zct::Mutex Class Reference

#include <Mutex.hpp>

Public Member Functions

 Mutex ()
 Construct a new mutex.
 
 ~Mutex ()
 Destroy the mutex.
 
MutexLockGuard lockGuard (k_timeout_t timeout)
 Get a lock guard for this mutex.
 
struct k_mutex * getZephyrMutex ()
 Get the underlying Zephyr mutex object.
 

Protected Attributes

struct k_mutex m_zephyrMutex
 

Detailed Description

Mutex is a C++ wrapper around a Zephyr mutex.

The recommended way to lock a mutex is to use the lockGuard() function which returns a MutexLockGuard object. This will automatically unlock the mutex when the lock guard goes out of scope.

Just like with the Zephyr mutex, they are not designed for use in interrupts.

See also
MutexLockGuard

Below is an example of how to use the Mutex class:

#include <zephyr/kernel.h>
#include <zephyr/logging/log.h>
LOG_MODULE_REGISTER(MutexExample, LOG_LEVEL_DBG);
int main() {
zct::Mutex mutex;
zct::MutexLockGuard lockGuard = mutex.lockGuard(K_MSEC(1000));
__ASSERT_NO_MSG(lockGuard.didGetLock());
LOG_INF("Mutex locked. It will be unlocked automatically when the lock guard goes out of scope.");
return 0;
}
Definition Mutex.hpp:14
bool didGetLock() const
Check if the mutex was successfully locked with this lock guard.
Definition Mutex.cpp:40
Definition Mutex.hpp:61
MutexLockGuard lockGuard(k_timeout_t timeout)
Get a lock guard for this mutex.
Definition Mutex.cpp:59
LOG_MODULE_REGISTER(EventThread, LOG_LEVEL_DBG)

Constructor & Destructor Documentation

◆ Mutex()

zct::Mutex::Mutex ( )

Construct a new mutex.

The mutex starts of in an unlocked state. Use a MutexLockGuard to lock the mutex.

◆ ~Mutex()

zct::Mutex::~Mutex ( )

Destroy the mutex.

Member Function Documentation

◆ getZephyrMutex()

struct k_mutex * zct::Mutex::getZephyrMutex ( )

Get the underlying Zephyr mutex object.

It is not recommended to use this function. Only use as an escape hatch if the provided C++ API is not sufficient.

Returns
A pointer to the Zephyr mutex object.

◆ lockGuard()

MutexLockGuard zct::Mutex::lockGuard ( k_timeout_t  timeout)

Get a lock guard for this mutex.

Note that this function may fail to lock the mutex. It is the callers responsibility to check if the lock was successful with didGetLock() after making this call.

Parameters
timeoutThe timeout for the lock. Pass K_FOREVER to wait indefinitely, or K_NO_WAIT to not wait at all.
Returns
A lock guard for this mutex.

Member Data Documentation

◆ m_zephyrMutex

struct k_mutex zct::Mutex::m_zephyrMutex
protected

The underlying Zephyr mutex object. Get access to this by calling getZephyrMutex().


The documentation for this class was generated from the following files: