Mutex
继承: RefCounted < Object
二元 Semaphore,用于在多 Thread 间进行同步。
描述
A synchronization mutex (mutual exclusion). This is used to synchronize multiple Threads, and is equivalent to a binary Semaphore. It guarantees that only one thread can access a critical section at a time.
This is a reentrant mutex, meaning that it can be locked multiple times by one thread, provided it also unlocks it as many times.
Warning: To ensure proper cleanup without crashes or deadlocks, the following conditions must be met:
When a Mutex's reference count reaches zero and it is therefore destroyed, no threads (including the one on which the destruction will happen) must have it locked.
When a Thread's reference count reaches zero and it is therefore destroyed, it must not have any mutex locked.
教程
方法
void |
lock() |
try_lock() |
|
void |
unlock() |
方法说明
void lock() 🔗
锁定此 Mutex,直到被当前所有者解锁为止。
注意:如果线程已经拥有互斥锁的所有权,该函数将无阻塞地返回。
尝试锁定该 Mutex,但不会阻塞。成功时返回 true,否则返回 false。
注意:如果该线程已经拥有了该互斥器的所有权,则函数返回 true。
void unlock() 🔗
Unlocks this Mutex, leaving it to other threads.
Note: If a thread called lock() or try_lock() multiple times while already having ownership of the mutex, it must also call unlock() the same number of times in order to unlock it correctly.
Warning: Calling unlock() more times than lock() on a given thread, thus ending up trying to unlock a non-locked mutex, is wrong and may causes crashes or deadlocks.