dsfml.system.mutex

$(U Mutex) stands for "MUTual EXclusion". A mutex is a synchronization object, used when multiple threads are involved.

When you want to protect a part of the code from being accessed simultaneously by multiple threads, you typically use a mutex. When a thread is locked by a mutex, any other thread trying to lock it will be blocked until the mutex is released by the thread that locked it. This way, you can allow only one thread at a time to access a critical region of your code.

Members

Classes

Mutex
class Mutex

Blocks concurrent access to shared resources from multiple threads.

Examples

1 // this is a critical resource that needs some protection
2 Database database;
3 auto mutex = Mutex();
4 
5 void thread1()
6 {
7 	   // this call will block the thread if the mutex is already locked by thread2
8    mutex.lock();
9    database.write(...);
10  *	   // if thread2 was waiting, it will now be unblocked
11    mutex.unlock();
12 }
13 
14 void thread2()
15 {
16    // this call will block the thread if the mutex is already locked by thread1
17    mutex.lock();
18    database.write(...);
19    mutex.unlock(); // if thread1 was waiting, it will now be unblocked
20 }

$(PARA Be very careful with mutexes. A bad usage can lead to bad problems, like deadlocks (two threads are waiting for each other and the application is globally stuck). To make the usage of mutexes more robust, particularly in environments where exceptions can be thrown, you should use the helper class $(LOCK_LINK) to lock/unlock mutexes. DSFML mutexes are recursive, which means that you can lock a mutex multiple times in the same thread without creating a deadlock. In this case, the first call to `lock()` behaves as usual, and the following ones have no effect. However, you must call `unlock()` exactly as many times as you called `lock()`. If you don't, the mutex won't be released. Note that the $(U Mutex) class is added for convenience, and is nothing more than a simnple wrapper around the existing core.sync.mutex.Mutex class.)

See Also

$(LOCK_LINK)

Meta