iOS 開發很難完全避開加鎖。同一份資源被多執行緒存取時,若沒有適當保護,資料錯亂往往在測試階段看不出來,上線後才突然爆掉。本文把常見的八種鎖集中比較一次。
1)@synchronized 關鍵字
2)NSLock 物件鎖
3)NSCondition
4)NSConditionLock 條件鎖
5)NSRecursiveLock 遞歸鎖
6)pthread_mutex 互斥鎖(C 語言)
7)dispatch_semaphore 信號量(GCD)
8)OSSpinLock 自旋鎖
用同一段程式,分別以八種方式各做一千萬次 lock/unlock,記錄總耗時:
#import <pthread.h>
#import <libkern/OSAtomic.h>
- (void)runLock {
NSUInteger count = 1000 * 10000; // 一千萬次
CFTimeInterval timeBefore, timeCurrent;
// @synchronized
id obj = [[NSObject alloc] init];
timeBefore = CFAbsoluteTimeGetCurrent();
for (NSUInteger i = 0; i < count; i++) {
@synchronized (obj) { }
}
timeCurrent = CFAbsoluteTimeGetCurrent();
NSLog(@"@synchronized: %f", timeCurrent - timeBefore);
// NSLock
NSLock *lock = [[NSLock alloc] init];
timeBefore = CFAbsoluteTimeGetCurrent();
for (NSUInteger i = 0; i < count; i++) {
[lock lock];
[lock unlock];
}
NSLog(@"NSLock: %f", CFAbsoluteTimeGetCurrent() - timeBefore);
// NSCondition
NSCondition *condition = [[NSCondition alloc] init];
timeBefore = CFAbsoluteTimeGetCurrent();
for (NSUInteger i = 0; i < count; i++) {
[condition lock];
[condition unlock];
}
NSLog(@"NSCondition: %f", CFAbsoluteTimeGetCurrent() - timeBefore);
// NSConditionLock
NSConditionLock *conditionLock = [[NSConditionLock alloc] initWithCondition:0];
timeBefore = CFAbsoluteTimeGetCurrent();
for (NSUInteger i = 0; i < count; i++) {
[conditionLock lock];
[conditionLock unlock];
}
NSLog(@"NSConditionLock: %f", CFAbsoluteTimeGetCurrent() - timeBefore);
// NSRecursiveLock
NSRecursiveLock *recursivelock = [[NSRecursiveLock alloc] init];
timeBefore = CFAbsoluteTimeGetCurrent();
for (NSUInteger i = 0; i < count; i++) {
[recursivelock lock];
[recursivelock unlock];
}
NSLog(@"NSRecursiveLock: %f", CFAbsoluteTimeGetCurrent() - timeBefore);
// pthread_mutex
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
timeBefore = CFAbsoluteTimeGetCurrent();
for (NSUInteger i = 0; i < count; i++) {
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
}
NSLog(@"pthread_mutex: %f", CFAbsoluteTimeGetCurrent() - timeBefore);
// dispatch_semaphore
dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
timeBefore = CFAbsoluteTimeGetCurrent();
for (NSUInteger i = 0; i < count; i++) {
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_semaphore_signal(semaphore);
}
NSLog(@"dispatch_semaphore: %f", CFAbsoluteTimeGetCurrent() - timeBefore);
// OSSpinLock
OSSpinLock spinlock = OS_SPINLOCK_INIT;
timeBefore = CFAbsoluteTimeGetCurrent();
for (NSUInteger i = 0; i < count; i++) {
OSSpinLockLock(&spinlock);
OSSpinLockUnlock(&spinlock);
}
NSLog(@"OSSpinLock: %f", CFAbsoluteTimeGetCurrent() - timeBefore);
}

從實測數據可以看出:OSSpinLock 效能最佳,GCD 的 dispatch_semaphore 緊追其後;而 NSConditionLock 與 @synchronized 相對較慢。
第一,這裡測的僅是 lock/unlock 本身的開銷。各鎖在使用條件上仍有差異,例如 NSLock 另外提供 tryLock、lockBeforeDate: 等變體,不同物件鎖的功能取向並不相同,有興趣可以逐一深入研究。
第二,也是更重要的:日常客戶端幾乎不會有千萬級的加解鎖操作,所以這些效能差距在實務上通常無感。真正該優先考量的反而是正確性:
· 自旋鎖不適合在鎖等待時間可能很長時使用,它會讓 CPU 空轉,而在行動裝置上這直接反映在電量與發熱;重載入時若脾氣不好還可能造成 priority inversion。
· 遞歸情境(同一執行緒重複進入)要用 NSRecursiveLock 或 pthread_mutexattr_settype 設為 recursive,一般的鎖會直接死鎖。
· 需要「等待某條件成立」而非單純互斥時,用 NSCondition 或 dispatch_semaphore 才對。
· @synchronized 最易讀,但每次都要付出查 objc 關聯表的成本,效能與可讀性之間要自己權衡。
結論:把鎖當成「溝通工具」而非「效能工具」來選,先問自己要的是互斥、遞歸還是條件等待,效能通常不是瓶頸所在。