Devel Lib
Devel::Threading::CMutex Class Reference

A class for handling recursive mutexes. More...

#include <Mutex.h>

Public Member Functions

 CMutex ()=default
 Default constructor for CMutex.
 
virtual ~CMutex ()=default
 Default virtual destructor for CMutex.
 
void lock () const
 Locks the mutex. If the mutex is currently locked by another thread, this call will block the calling thread until the mutex is unlocked.
 
void unlock () const
 Unlocks the mutex.
 
bool tryLock () const
 Attempts to lock the mutex. If the mutex is not available for locking, this function returns immediately with a value of false. If the mutex is available for locking, the function locks the mutex and returns true. More...
 

Detailed Description

A class for handling recursive mutexes.

This class encapsulates a std::recursive_mutex, providing an interface for locking and unlocking the mutex.

Example

This class must be used when you want to protect a shared resource from simultaneous access by multiple threads. Here is a simple usage example:

#include "CMutex.h"
#include <thread>
int sharedCounter = 0;
void incrementCounter() {
mutex.lock();
sharedCounter++;
mutex.unlock();
}
int main() {
// Launch two threads that both increment the shared counter
std::thread t1(incrementCounter);
std::thread t2(incrementCounter);
// Wait for both threads to finish
t1.join();
t2.join();
// Print the final value of the counter
std::cout << "Final counter value: " << sharedCounter << std::endl;
return 0;
}
A class for handling recursive mutexes.
Definition: Mutex.h:47
void lock() const
Locks the mutex. If the mutex is currently locked by another thread, this call will block the calling...
Definition: Mutex.h:58
void unlock() const
Unlocks the mutex.
Definition: Mutex.h:63

Member Function Documentation

◆ tryLock()

bool Devel::Threading::CMutex::tryLock ( ) const
inline

Attempts to lock the mutex. If the mutex is not available for locking, this function returns immediately with a value of false. If the mutex is available for locking, the function locks the mutex and returns true.

Returns
True if the mutex was successfully locked, false otherwise.

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