dsfml.system.lock

$(U Lock) is a RAII wrapper for DSFML's 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, $(U Lock) should always be used to lock/unlock a mutex.

Note that this structure is provided for convenience when porting projects from SFML to DSFML. The same effect can be achieved with scope guards and Mutex.

Members

Structs

Lock
struct Lock

Automatic wrapper for locking and unlocking mutexes.

Examples

1 auto mutex = Mutex();
2 
3 void function()
4 {
5    auto lock = Lock(mutex); // mutex is now locked
6 
7  *	   // mutex is unlocked if this function throws
8    functionThatMayThrowAnException();
9 
10    if (someCondition)
11        return; // mutex is unlocked
12 
13 } // mutex is unlocked

$(PARA 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.)

1 auto mutex = Mutex();
2 
3 void function()
4 {
5    {
6      auto lock = Lock(mutex);
7      codeThatRequiresProtection();
8 
9    } // mutex is unlocked here
10 
11    codeThatDoesntCareAboutTheMutex();
12 }

$(PARA 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

$(MUTEX_LINK)

Meta