os_unfair_lock是一种底层锁,允许waiters在竞争时有效阻塞。
通常,应优先选择使用高级同步工具。如 pthread、dispatch 等提供的同步方案。
存储在锁中的值应被认为是不透明的,并且在实现中定义。其包含线程信息,系统可用于解决优先级反转问题。
加锁和解锁必须在同一线程,负责会引起程序异常终止。
用于取代OSSpinLock,尝试获取已加锁的线程无需忙等(是互斥锁),解锁时由内核唤醒。和OSSpinLock一样,os_unfair_lock也没有加强公平性和顺序。例如,释放锁的线程可能立即再次加锁,而之前等待锁的线程唤醒后没有机会尝试加锁。这样有利于提高性能,但也造成了饥饿(starvation)。Starvation 指贪婪线程占用共享资源太长时间,其他线程无法访问共享资源、无法取得进展。例如,某对象的同步方法占用时间过长,并且频繁调用,其他线程尝试调用该方法时会被堵塞,处于 starvation。
#include <os/lock.h>
* Low-level lock that allows waiters to block efficiently(有效) on contention(竞争).
*
* In general, higher level synchronization primitives such as those provided by
* the pthread or dispatch subsystems should be preferred.
*
* The values stored in the lock should be considered opaque and implementation
* defined, they contain thread ownership information that the system may use
* to attempt to resolve priority inversions.
*
* This lock must be unlocked from the same thread that locked it, attempts to
* unlock from a different thread will cause an assertion aborting the process.
*
* This lock must not be accessed from multiple processes or threads via shared
* or multiply-mapped memory, the lock implementation relies on the address of
* the lock value and owning process.
*
* Must be initialized with OS_UNFAIR_LOCK_INIT
*
* @discussion
* Replacement for the deprecated OSSpinLock. Does not spin on contention but
* waits in the kernel to be woken up by an unlock.
*
* As with OSSpinLock there is no attempt at fairness or lock ordering, e.g. an
* unlocker can potentially immediately reacquire the lock before a woken up
* waiter gets an opportunity to attempt to acquire the lock. This may be
* advantageous for performance reasons, but also makes starvation of waiters a
* possibility.
参考:
os_unfair_lock_lock
Starvation and Livelock
解说os_unfair_lock
网友评论