iOS中有哪些鎖呢?
OSSpinLock,dispatch_semaphore_t,os_unfair_lock,pthread_mutex_t,NSLock,NSCondition,pthread_mutext_t(recursive),NSRecursiveLock,NSConditionLock,@synchronized 等等,這么多的鎖在開發(fā)中要如何選擇呢?
各個鎖的性能
首先我們通過代碼來看看鎖的性能
int kc_runTimes = 100000;
/** OSSpinLock 性能 */
{
OSSpinLock kc_spinlock = OS_SPINLOCK_INIT;
double_t kc_beginTime = CFAbsoluteTimeGetCurrent();
for (int i=0 ; i < kc_runTimes; i++) {
OSSpinLockLock(&kc_spinlock); //解鎖
OSSpinLockUnlock(&kc_spinlock);
}
double_t kc_endTime = CFAbsoluteTimeGetCurrent() ;
HFLog(@"OSSpinLock: %f ms",(kc_endTime - kc_beginTime)*1000);
}
/** dispatch_semaphore_t 性能 */
{
dispatch_semaphore_t kc_sem = dispatch_semaphore_create(1);
double_t kc_beginTime = CFAbsoluteTimeGetCurrent();
for (int i=0 ; i < kc_runTimes; i++) {
dispatch_semaphore_wait(kc_sem, DISPATCH_TIME_FOREVER);
dispatch_semaphore_signal(kc_sem);
}
double_t kc_endTime = CFAbsoluteTimeGetCurrent() ;
HFLog(@"dispatch_semaphore_t: %f ms",(kc_endTime - kc_beginTime)*1000);
}
/** os_unfair_lock_lock 性能 */
{
os_unfair_lock kc_unfairlock = OS_UNFAIR_LOCK_INIT;
double_t kc_beginTime = CFAbsoluteTimeGetCurrent();
for (int i=0 ; i < kc_runTimes; i++) {
os_unfair_lock_lock(&kc_unfairlock);
os_unfair_lock_unlock(&kc_unfairlock);
}
double_t kc_endTime = CFAbsoluteTimeGetCurrent() ;
HFLog(@"os_unfair_lock_lock: %f ms",(kc_endTime - kc_beginTime)*1000);
}
/** pthread_mutex_t 性能 */
{
pthread_mutex_t kc_metext = PTHREAD_MUTEX_INITIALIZER;
double_t kc_beginTime = CFAbsoluteTimeGetCurrent();
for (int i=0 ; i < kc_runTimes; i++) {
pthread_mutex_lock(&kc_metext);
pthread_mutex_unlock(&kc_metext);
}
double_t kc_endTime = CFAbsoluteTimeGetCurrent() ;
HFLog(@"pthread_mutex_t: %f ms",(kc_endTime - kc_beginTime)*1000);
}
/** NSlock 性能 */
{
NSLock *kc_lock = [NSLock new];
double_t kc_beginTime = CFAbsoluteTimeGetCurrent();
for (int i=0 ; i < kc_runTimes; i++) {
[kc_lock lock];
[kc_lock unlock];
}
double_t kc_endTime = CFAbsoluteTimeGetCurrent() ;
HFLog(@"NSlock: %f ms",(kc_endTime - kc_beginTime)*1000);
}
/** NSCondition 性能 */
{
NSCondition *kc_condition = [NSCondition new];
double_t kc_beginTime = CFAbsoluteTimeGetCurrent();
for (int i=0 ; i < kc_runTimes; i++) {
[kc_condition lock];
[kc_condition unlock];
}
double_t kc_endTime = CFAbsoluteTimeGetCurrent() ;
HFLog(@"NSCondition: %f ms",(kc_endTime - kc_beginTime)*1000);
}
/** PTHREAD_MUTEX_RECURSIVE 性能 */
{
pthread_mutex_t kc_metext_recurive;
pthread_mutexattr_t attr;
pthread_mutexattr_init (&attr);
pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init (&kc_metext_recurive, &attr);
double_t kc_beginTime = CFAbsoluteTimeGetCurrent();
for (int i=0 ; i < kc_runTimes; i++) {
pthread_mutex_lock(&kc_metext_recurive);
pthread_mutex_unlock(&kc_metext_recurive);
}
double_t kc_endTime = CFAbsoluteTimeGetCurrent() ;
HFLog(@"PTHREAD_MUTEX_RECURSIVE: %f ms",(kc_endTime - kc_beginTime)*1000);
}
/** NSRecursiveLock 性能 */
{
NSRecursiveLock *kc_recursiveLock = [NSRecursiveLock new];
double_t kc_beginTime = CFAbsoluteTimeGetCurrent();
for (int i=0 ; i < kc_runTimes; i++) {
[kc_recursiveLock lock];
[kc_recursiveLock unlock];
}
double_t kc_endTime = CFAbsoluteTimeGetCurrent() ;
HFLog(@"NSRecursiveLock: %f ms",(kc_endTime - kc_beginTime)*1000);
}
/** NSConditionLock 性能 */
{
NSConditionLock *kc_conditionLock = [NSConditionLock new];
double_t kc_beginTime = CFAbsoluteTimeGetCurrent();
for (int i=0 ; i < kc_runTimes; i++) {
[kc_conditionLock lock];
[kc_conditionLock unlock];
}
double_t kc_endTime = CFAbsoluteTimeGetCurrent() ;
HFLog(@"NSConditionLock: %f ms",(kc_endTime - kc_beginTime)*1000);
}
/** @synchronized 性能 */
{
double_t kc_beginTime = CFAbsoluteTimeGetCurrent();
for (int i=0 ; i < kc_runTimes; i++) {
@synchronized(self) {}
}
double_t kc_endTime = CFAbsoluteTimeGetCurrent() ;
HFLog(@"@synchronized: %f ms",(kc_endTime - kc_beginTime)*1000);
}
代碼邏輯很簡單,就是循環(huán)10萬次的加解鎖,看看需要耗費的時間
真機iphoneXR運行結(jié)果:
OSSpinLock: 1.433015 ms
dispatch_semaphore_t: 2.267957 ms
os_unfair_lock_lock: 2.338052 ms
pthread_mutex_t: 2.584100 ms
NSlock: 2.802968 ms
NSCondition: 2.210975 ms
PTHREAD_MUTEX_RECURSIVE: 2.773046 ms
NSRecursiveLock: 3.018975 ms
NSConditionLock: 5.580902 ms
@synchronized: 9.202957 ms
真機iphone12 mini運行結(jié)果
OSSpinLock: 0.748038 ms
dispatch_semaphore_t: 1.023054 ms
os_unfair_lock_lock: 0.805020 ms
pthread_mutex_t: 0.934958 ms
NSlock: 1.582980 ms
NSCondition: 1.513004 ms
PTHREAD_MUTEX_RECURSIVE: 2.305984 ms
NSRecursiveLock: 2.532005 ms
NSConditionLock: 8.258939 ms
@synchronized: 3.880978 ms
可以看到@synchronized性能上優(yōu)化了很多。
synchronized的使用
我們先來分析最常用的synchronized,我們知道synchronized既可以多線程操作也可以嵌套使用比如:
@synchronized (self) {
NSLog(@"2222222");
@synchronized (self) {
NSLog(@"333333");
@synchronized (self) {
NSLog(@"1111111");
}
}
}
輸出結(jié)果:
2222222
333333
1111111
多線程并且嵌套
for (int i=0; i<10; i++) {
dispatch_async(dispatch_get_global_queue(0, 0), ^{
@synchronized (self) {
NSLog(@"----i:%d", i);
@synchronized (self) {
NSLog(@"+++++++i:%d", i);
}
}
});
}
輸出結(jié)果:
----i:0
+++++++i:0
----i:1
+++++++i:1
----i:2
+++++++i:2
----i:3
+++++++i:3
----i:4
+++++++i:4
----i:5
+++++++i:5
----i:6
+++++++i:6
----i:7
+++++++i:7
----i:8
+++++++i:8
----i:9
+++++++i:9
用起來似乎挺好用的,嵌套多線程都不會導(dǎo)致死鎖,那我們來研究一下synchronized底層源碼
synchronized源碼分析
int main(int argc, char * argv[]) {
NSString * appDelegateClassName;
@autoreleasepool {
// Setup code that might create autoreleased objects goes here.
appDelegateClassName = NSStringFromClass([AppDelegate class]);
@synchronized (appDelegateClassName) {
NSLog(@"1111111111");
}
}
return UIApplicationMain(argc, argv, nil, appDelegateClassName);
}
xcrun -sdk iphonesimulator clang -rewrite-objc main.m
{
__AtAutoreleasePool __autoreleasepool;
appDelegateClassName = NSStringFromClass(((Class (*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("AppDelegate"), sel_registerName("class")));
{
id _rethrow = 0;
id _sync_obj = (id)appDelegateClassName;
objc_sync_enter(_sync_obj);
try
{
struct _SYNC_EXIT
{
_SYNC_EXIT(id arg) : sync_exit(arg){}
~_SYNC_EXIT() {
objc_sync_exit(sync_exit);
}
id sync_exit;
} _sync_exit(_sync_obj);
NSLog((NSString *)&__NSConstantStringImpl__var_folders_w3_866g87vs39x5nbg5g4xtzqxc0000gn_T_main_42da63_mi_0);
}
catch (id e) {_rethrow = e;}
{
struct _FIN { _FIN(id reth) : rethrow(reth) {}
~_FIN() { if (rethrow) objc_exception_throw(rethrow); }
id rethrow;
} _fin_force_rethow(_rethrow);
}
}
}
return UIApplicationMain(argc, argv, __null, appDelegateClassName);
通過xcrun可以分析出synchronized實際就是objc_sync_enter(_sync_obj); objc_sync_exit(sync_exit);加鎖,這樣我們就可以通過符號斷點到objc_sync_enter

符號斷點到了
libobjc.A.dylib objc_sync_enter:,這邊objc_sync_enter在libobjc源碼里面。注意我們的目的:為什么能夠嵌套加鎖,為什么可以多線程加鎖
int objc_sync_enter(id obj)
{
int result = OBJC_SYNC_SUCCESS;
if (obj) {
SyncData* data = id2data(obj, ACQUIRE);
ASSERT(data);
data->mutex.lock();
} else {
// @synchronized(nil) does nothing
if (DebugNilSync) {
_objc_inform("NIL SYNC DEBUG: @synchronized(nil); set a breakpoint on objc_sync_nil to debug");
}
objc_sync_nil();
}
return result;
}
int objc_sync_exit(id obj)
{
int result = OBJC_SYNC_SUCCESS;
if (obj) {
SyncData* data = id2data(obj, RELEASE);
if (!data) {
result = OBJC_SYNC_NOT_OWNING_THREAD_ERROR;
} else {
bool okay = data->mutex.tryUnlock();
if (!okay) {
result = OBJC_SYNC_NOT_OWNING_THREAD_ERROR;
}
}
} else {
// @synchronized(nil) does nothing
}
return result;
}
源碼看起來并不多啊,但是注意到參數(shù)obj不能為nil否則會報錯
源碼里面首先獲取了SyncData,然后data->mutex.lock,那這個SyncData是什么呢?先看看他的數(shù)據(jù)結(jié)構(gòu)
typedef struct alignas(CacheLineSize) SyncData {
struct SyncData* nextData; // 跟指針一樣指向下一個對象,所以這應(yīng)該是一個鏈表
DisguisedPtr<objc_object> object; // 關(guān)聯(lián)指針,關(guān)聯(lián)著當前obj
int32_t threadCount; // number of THREADS using this block 記錄線程數(shù)量
recursive_mutex_t mutex; // 底層的嵌套鎖,所以可以嵌套使用
} SyncData;
單純的看這個結(jié)構(gòu)體似乎了解了一些,接下來繼續(xù)看看SyncData的生成SyncData* data = id2data(obj, ACQUIRE);
#define LOCK_FOR_OBJ(obj) sDataLists[obj].lock
#define LIST_FOR_OBJ(obj) sDataLists[obj].data
static StripedMap<SyncList> sDataLists;
static SyncData* id2data(id object, enum usage why)
{
spinlock_t *lockp = &LOCK_FOR_OBJ(object);
SyncData **listp = &LIST_FOR_OBJ(object);
SyncData* result = NULL;
#if SUPPORT_DIRECT_THREAD_KEYS
// Check per-thread single-entry fast cache for matching object
// 檢查每線程單條目快速緩存中是否有匹配的對象
bool fastCacheOccupied = NO;
// TLS 是系統(tǒng)為線程單獨提供的私有空間,這邊返回的是當前線程綁定的SyncData
SyncData *data = (SyncData *)tls_get_direct(SYNC_DATA_DIRECT_KEY);
if (data) {
fastCacheOccupied = YES;
if (data->object == object) {
// Found a match in fast cache.
uintptr_t lockCount;
result = data;
lockCount = (uintptr_t)tls_get_direct(SYNC_COUNT_DIRECT_KEY);
if (result->threadCount <= 0 || lockCount <= 0) {
_objc_fatal("id2data fastcache is buggy");
}
switch(why) {
case ACQUIRE: {
lockCount++;
tls_set_direct(SYNC_COUNT_DIRECT_KEY, (void*)lockCount);
break;
}
case RELEASE:
lockCount--;
tls_set_direct(SYNC_COUNT_DIRECT_KEY, (void*)lockCount);
if (lockCount == 0) {
// remove from fast cache
tls_set_direct(SYNC_DATA_DIRECT_KEY, NULL);
// atomic because may collide with concurrent ACQUIRE
OSAtomicDecrement32Barrier(&result->threadCount);
}
break;
case CHECK:
// do nothing
break;
}
return result;
}
}
#endif
// Check per-thread cache of already-owned locks for matching object
// 檢查已擁有鎖的每個線程緩存中是否存在匹配的對象
SyncCache *cache = fetch_cache(NO);
if (cache) {
unsigned int I;
for (i = 0; i < cache->used; i++) {
SyncCacheItem *item = &cache->list[I];
if (item->data->object != object) continue;
// Found a match.
result = item->data;
if (result->threadCount <= 0 || item->lockCount <= 0) {
_objc_fatal("id2data cache is buggy");
}
switch(why) {
case ACQUIRE:
item->lockCount++;
break;
case RELEASE:
item->lockCount--;
if (item->lockCount == 0) {
// remove from per-thread cache
cache->list[i] = cache->list[--cache->used];
// atomic because may collide with concurrent ACQUIRE
OSAtomicDecrement32Barrier(&result->threadCount);
}
break;
case CHECK:
// do nothing
break;
}
return result;
}
}
// Thread cache didn't find anything.
// Walk in-use list looking for matching object
// Spinlock prevents multiple threads from creating multiple
// locks for the same new object.
// We could keep the nodes in some hash table if we find that there are
// more than 20 or so distinct locks active, but we don't do that now.
lockp->lock();
{
SyncData* p;
SyncData* firstUnused = NULL;
for (p = *listp; p != NULL; p = p->nextData) {
if ( p->object == object ) {
result = p;
// atomic because may collide with concurrent RELEASE
OSAtomicIncrement32Barrier(&result->threadCount);
goto done;
}
if ( (firstUnused == NULL) && (p->threadCount == 0) )
firstUnused = p;
}
// no SyncData currently associated with object
if ( (why == RELEASE) || (why == CHECK) )
goto done;
// an unused one was found, use it
if ( firstUnused != NULL ) {
result = firstUnused;
result->object = (objc_object *)object;
result->threadCount = 1;
goto done;
}
}
// Allocate a new SyncData and add to list.
// XXX allocating memory with a global lock held is bad practice,
// might be worth releasing the lock, allocating, and searching again.
// But since we never free these guys we won't be stuck in allocation very often.
// 創(chuàng)建SyncData,初始化數(shù)據(jù),也就是第一次加鎖時進來的代碼邏輯
posix_memalign((void **)&result, alignof(SyncData), sizeof(SyncData));
result->object = (objc_object *)object;
result->threadCount = 1;
new (&result->mutex) recursive_mutex_t(fork_unsafe_lock);
result->nextData = *listp;
*listp = result;
done:
lockp->unlock();
if (result) {
// Only new ACQUIRE should get here.
// All RELEASE and CHECK and recursive ACQUIRE are
// handled by the per-thread caches above.
if (why == RELEASE) {
// Probably some thread is incorrectly exiting
// while the object is held by another thread.
return nil;
}
if (why != ACQUIRE) _objc_fatal("id2data is buggy");
if (result->object != object) _objc_fatal("id2data is buggy");
#if SUPPORT_DIRECT_THREAD_KEYS
if (!fastCacheOccupied) {
// Save in fast thread cache
tls_set_direct(SYNC_DATA_DIRECT_KEY, result);
tls_set_direct(SYNC_COUNT_DIRECT_KEY, (void*)1);
} else
#endif
{
// Save in thread cache
if (!cache) cache = fetch_cache(YES);
cache->list[cache->used].data = result;
cache->list[cache->used].lockCount = 1;
cache->used++;
}
}
return result;
}
代碼量有點多我們先折疊一下,看看整體注釋

注意:
done里面的代碼,這邊生成的 result會根據(jù)條件將result存儲在線程的獨立空間tls或cache,方便下一次取出來做判斷,而if(data)和if(cache)里面的代碼內(nèi)容一模一樣函數(shù)一開始從
static StripedMap<SyncList> sDataLists;哈希表里面取出lockp和listp兩個字段,而后面生成的SyncData存放在listp指針,說明數(shù)據(jù)結(jié)構(gòu)是哈希表,而Syncdata又是一個鏈表,所以整體結(jié)構(gòu)是哈希鏈表接下來我們通過示例來調(diào)試研究看看
首先是相同對象的嵌套
@synchronized (obj) {
NSLog(@"bbbbbb");
@synchronized (obj) {
NSLog(@"aaaaaa");
}
}
調(diào)試objc_sync_enter,第一次代碼進入到id2data時創(chuàng)建了SyncData對象,并將對象存儲在TLS線程獨立空間里面和哈希表里,第二次進來時通過tls_get_direct獲取到了SyncData,而SyncData里面的objcet跟當前的object一樣,所以直接進入到if (data)邏輯里面的case ACQUIRE,lockCount++
不同對象的嵌套
@synchronized (obj) {
NSLog(@"bbbbbb");
@synchronized (p) {
NSLog(@"aaaaaa");
}
}
調(diào)試objc_sync_enter,第一次代碼進入到id2data時創(chuàng)建了SyncData對象,并將對象存儲在TLS線程獨立空間里面和哈希表里,第二次進來時listp為空,tls_get_direct獲取到了SyncData=NULL,所以會創(chuàng)建SyncData對象,并且通過listp掛到哈希表里。
多線程相同對象
@synchronized (obj) {
NSLog(@"bbbbbb");
dispatch_async(dispatch_get_global_queue(0, 0), ^{
@synchronized (obj) {
NSLog(@"aaaaaa");
}
});
}
調(diào)試objc_sync_enter,第一次代碼進入到id2data時創(chuàng)建了SyncData對象,并將對象存儲在TLS線程獨立空間里面和哈希表里,第二次進來時因為對象是一樣的所以listp有值,但是tls_get_direct取到的值為空(線程不一樣),所以直接來到for (p = *listp; p != NULL; p = p->nextData)鏈表遍歷,進而對threadCount++
這樣我們大致可以了解整個鎖的結(jié)構(gòu)

總結(jié):
整體結(jié)構(gòu)是一個哈希鏈表,通過對obj的哈希來存放SyncData,
兩種存儲方式TLS/Cache
第一次加鎖時,創(chuàng)建SyncData, 標記threadcount=1
后面在進來,會判斷是否是同一個對象,
如果是同一個對象同一個線程TLS->lock++
如果是同一個對象不同線程TLS找不到SyncData,threadCount++
如果是不同對象同一個線程 創(chuàng)建一個新的SyncData,插入到obj哈希對應(yīng)鏈表位置
解鎖:lock--; threadCount--