SFML - Simple and Fast Multimedia Library

SFML 2.6.1

- Main Page
- Related Pages
- Topics
- Namespaces
- Classes
- Files

- Class List
- Class Index
- Class Hierarchy
- Class Members

Loading...
Searching...
No Matches
Public Member Functions | List of all members
sf::Lock Class Reference
System module

Automatic wrapper for locking and unlocking mutexes. More...

`#include <SFML/System/Lock.hpp>`

Inheritance diagram for sf::Lock:

## Public Member Functions
| Lock (Mutex &mutex)
| Construct the lock with a target mutex.
| ~Lock ()
| Destructor.

## Detailed Description

Automatic wrapper for locking and unlocking mutexes.

sf::Lock is a RAII wrapper for sf::Mutex.

By unlocking it in its destructor, it ensures that the mutex will always be released when the current scope (most likely a function) ends. This is even more important when an exception or an early return statement can interrupt the execution flow of the function.

For maximum robustness, sf::Lock should always be used to lock/unlock a mutex.

Usage example:

sf::Mutex mutex;
void function()
{
sf::Lock lock(mutex); // mutex is now locked
functionThatMayThrowAnException(); // mutex is unlocked if this function throws
if (someCondition)
return; // mutex is unlocked
} // mutex is unlocked
sf::Lock
Automatic wrapper for locking and unlocking mutexes.
Definition Lock.hpp:44
sf::Mutex
Blocks concurrent access to shared resources from multiple threads.
Definition Mutex.hpp:48

Because the mutex is not explicitly unlocked in the code, it may remain locked longer than needed. If the region of the code that needs to be protected by the mutex is not the entire function, a good practice is to create a smaller, inner scope so that the lock is limited to this part of the code.

sf::Mutex mutex;
void function()
{
{
sf::Lock lock(mutex);
codeThatRequiresProtection();
} // mutex is unlocked here
codeThatDoesntCareAboutTheMutex();
}

Having a mutex locked longer than required is a bad practice which can lead to bad performances. Don't forget that when a mutex is locked, other threads may be waiting doing nothing until it is released.

See also
  sf::Mutex

Definition at line 43 of file Lock.hpp.

## Constructor & Destructor Documentation

## ◆ Lock()

sf::Lock::Lock | ( | Mutex & | mutex | ) |
| explicit

Construct the lock with a target mutex.

The mutex passed to sf::Lock is automatically locked.

Parameters

  mutex | Mutex to lock

## ◆ ~Lock()

sf::Lock::~Lock | ( |  | ) |

Destructor.

The destructor of sf::Lock automatically unlocks its mutex.

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

- Lock.hpp