概念
自旋鎖:
線程反復(fù)檢查鎖變量是否可用。由于線程在這一過程中保持執(zhí)行, 因此是一種忙等待。一旦獲取了自旋鎖,線程會一直保持該鎖,直至顯式釋 放自旋鎖。 自旋鎖避免了進(jìn)程上下文的調(diào)度開銷,因此對于線程只會阻塞很 短時間的場合是有效的。###互斥鎖
是一種用于多線程編程中,防止兩條線程同時對同一公共資源(比 如全局變量)進(jìn)行讀寫的機(jī)制。該目的通過將代碼切片成一個一個的臨界區(qū)而達(dá)成?;コ怄i有NSLock,pthread_mutex,@synchronized
條件鎖:
就是條件變量,當(dāng)進(jìn)程的某些資源要求不滿足時就進(jìn)入休眠,也就是鎖住了。當(dāng)資源被分配到了,條件鎖打開,進(jìn)程繼續(xù)運(yùn)行 NSCondition,NSConditionLock
遞歸鎖
就是同一個線程可以加鎖N次而不會引發(fā)死鎖,NSRecursiveLock,pthread_mutex(recursive)
信號量(semaphore)
是一種更高級的同步機(jī)制,互斥鎖可以說是semaphore在僅取值0/1時的特例。信號量可以有更多的取值空間,用來實(shí)現(xiàn)更加復(fù)雜的同步,而不單單是線程間互斥。dispatch_semaphore
其實(shí)基本的鎖就包括了三類 自旋鎖 互斥鎖 讀寫鎖,
其他的比如條件鎖,遞歸鎖,信號量都是上層的封裝和實(shí)現(xiàn)!
讀寫鎖
讀寫鎖實(shí)際是一種特殊的自旋鎖,它把對共享資源的訪問者劃分成讀者和寫者,讀者只對共享資源 進(jìn)行讀訪問,寫者則需要對共享資源進(jìn)行寫操作。這種鎖相對于自旋鎖而言,能提高并發(fā)性,因?yàn)樵诙嗵幚砥飨到y(tǒng)中,它允許同時有多個讀者來訪問共享資源,最大可能的讀者數(shù)為實(shí)際的邏輯CPU 數(shù)。寫者是排他性的,一個讀寫鎖同時只能有一個寫者或多個讀者(與CPU數(shù)相關(guān)),但不能同時既有讀者又有寫者。在讀寫鎖保持期間也是搶占失效的。
如果讀寫鎖當(dāng)前沒有讀者,也沒有寫者,那么寫者可以立刻獲得讀寫鎖,否則它必須自旋在那里,直到?jīng)]有任何寫者或讀者。如果讀寫鎖沒有寫者,那么讀者可以立即獲得該讀寫鎖,否則讀者必須自旋在那里,直到寫者釋放該讀寫鎖。
一次只有一個線程可以占有寫模式的讀寫鎖, 但是可以有多個線程同時占有讀模式的讀寫鎖. 正是因?yàn)檫@個特性,當(dāng)讀寫鎖是寫加鎖狀態(tài)時, 在這個鎖被解鎖之前, 所有試圖對這個鎖加鎖的線程都會被阻塞.當(dāng)讀寫鎖在讀加鎖狀態(tài)時, 所有試圖以讀模式對它進(jìn)行加鎖的線程都可以得到訪問權(quán), 但是如果線程希望以寫模式對此鎖進(jìn)行加鎖, 它必須直到所有的線程釋放鎖.通常, 當(dāng)讀寫鎖處于讀模式鎖住狀態(tài)時, 如果有另外線程試圖以寫模式加鎖, 讀寫鎖通常會阻塞隨后的讀模式鎖請求, 這樣可以避免讀模式鎖?期占用, 而等待的寫模式鎖請求?期阻塞.
讀寫鎖適合于對數(shù)據(jù)結(jié)構(gòu)的讀次數(shù)比寫次數(shù)多得多的情況. 因?yàn)? 讀模式鎖定時可以共享, 以寫模式鎖住時意味著獨(dú)占, 所以讀寫鎖又叫共享-獨(dú)占鎖.
include <pthread.h>
int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock, const pthread_rwlockattr_t *restrict attr);
int pthread_rwlock_destroy(pthread_rwlock_t *rwlock)
成功則返回0, 出錯則返回錯誤編號.
同互斥量以上, 在釋放讀寫鎖占用的內(nèi)存之前, 需要先通過pthread_rwlock_destroy對讀寫鎖進(jìn)行清理工作, 釋
放由init分配的資源.
include <pthread.h>
int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
成功則返回0, 出錯則返回錯誤編號.
這3個函數(shù)分別實(shí)現(xiàn)獲取讀鎖, 獲取寫鎖和釋放鎖的操作. 獲取鎖的兩個函數(shù)是阻塞操作, 同樣, 非阻塞的函數(shù)為:
include <pthread.h>
int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);
成功則返回0, 出錯則返回錯誤編號.
非阻塞的獲取鎖操作, 如果可以獲取則返回0, 否則返回錯誤的EBUSY.

synchronized
沒用synchronized之前
- (void)lg_testSaleTicket{
dispatch_async(dispatch_get_global_queue(0, 0), ^{
for (int i = 0; i < 5; i++) {
[self saleTicket];
}
});
dispatch_async(dispatch_get_global_queue(0, 0), ^{
for (int i = 0; i < 5; i++) {
[self saleTicket];
}
});
dispatch_async(dispatch_get_global_queue(0, 0), ^{
for (int i = 0; i < 3; i++) {
[self saleTicket];
}
});
dispatch_async(dispatch_get_global_queue(0, 0), ^{
for (int i = 0; i < 10; i++) {
[self saleTicket];
}
});
}
- (void)saleTicket{
if (self.ticketCount > 0) {
self.ticketCount--;
sleep(0.1);
NSLog(@"當(dāng)前余票還剩:%ld張",self.ticketCount);
}else{
NSLog(@"當(dāng)前車票已售罄");
}
}
打印結(jié)果
當(dāng)前余票還剩:19張
當(dāng)前余票還剩:18張
當(dāng)前余票還剩:16張
當(dāng)前余票還剩:16張
亂序執(zhí)行
當(dāng)前余票還剩:4張
當(dāng)前余票還剩:3張
當(dāng)前余票還剩:2張
當(dāng)前余票還剩:2張
當(dāng)前余票還剩:1張
當(dāng)前余票還剩:0張
當(dāng)前車票已售罄
修改后
- (void)saleTicket{
@synchronized (self) {
if (self.ticketCount > 0) {
self.ticketCount--;
sleep(0.1);
NSLog(@"當(dāng)前余票還剩:%ld張",self.ticketCount);
}else{
NSLog(@"當(dāng)前車票已售罄");
}
}
}
//打印結(jié)果
當(dāng)前余票還剩:19
當(dāng)前余票還剩:18
//順序執(zhí)行
當(dāng)前余票還剩:1
當(dāng)前余票還剩:0
當(dāng)前車票已售罄
當(dāng)前車票已售罄
當(dāng)前車票已售罄
synchronized到底做了什么事呢?下面我們來探索一下
通過clang看synchronized的實(shí)現(xiàn)過程
int main2(){
NSObject *objec = [NSObject new];
@synchronized (objec) {
}
return 1;
}
clang后
NSObject *objec = ((NSObject *(*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("NSObject"), sel_registerName("new"));
{ id _rethrow = 0; id _sync_obj = (id)objec; 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);
} 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);}
}
首先下符號斷點(diǎn)確定objc_sync_enter和objc_sync_exit所在的庫,可知在libobjc.A.dylib,然后看源碼
objc_sync_enter
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;
}
當(dāng)傳入的obj有值時,我們通過id2data獲取一個對象data,然后對data的mutex進(jìn)行l(wèi)ock,如果obj沒有值,@synchronized(nil)什么都不做
objc_sync_exit
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;
}
如果obj為nil,則@synchronized加鎖失敗,if通過id2data取到的data為空則返回
OBJC_SYNC_NOT_OWNING_THREAD_ERROR,如果data的mutex開鎖失敗也返回OBJC_SYNC_NOT_OWNING_THREAD_ERROR,成功則返回OBJC_SYNC_SUCCESS。
對重要函數(shù)id2data進(jìn)行分析
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;
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.
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;
}
1.第一次objc_sync_enter
從線程局部存儲中尋找,沒有找到從fetch_cache中也沒有找到,listp也沒有該對象的元素,則重新創(chuàng)建,然后存儲起來。
2.同一線程同一對象第二次objc_sync_enter
可以從線程局部存儲(TS L)中直接找到,然后對lockCount++,存儲都tls中
3.不同線程的同一個對象objc_sync_enter
因?yàn)椴皇峭痪€程,我們無法從tsl中直接找到,在fetch_cache能找不到,因?yàn)閒etch_cache也是在tsl中找的,遍歷對象的listp列表,對對象的threadCount加1.
4.不同線程的同一個對象objc_sync_exit
我們能從fetch_cache找到對象,然后對lockCount減1,如果threadCount和lockCount都等于0,則讓threadCount減去1
SyncData對象分析
recursive_mutex_t 遞歸互斥鎖
nextData 形成連表效果
threadCount 記錄線程個數(shù)。
object 存儲對象的hash值
synchronized注意點(diǎn)
1.synchronized 性能問題,
2.synchronized鎖的對象的聲明周期
3.如果在多個地方synchronized同一個對象,則查找更慢,性能更差
TLS 線程相關(guān)解釋
線程局部存儲(Thread Local Storage,TLS): 是操作系統(tǒng)為線程單獨(dú)提供的私有空間,通常只有有限的容量。Linux系統(tǒng)下通常通過pthread庫中的
pthread_key_create()、pthread_getspecific()、pthread_setspecific()、pthread_key_delete()
代碼示例
- (void)lg_testRecursive{
for (int i= 0; i<100; i++) {
dispatch_async(dispatch_get_global_queue(0, 0), ^{
static void (^testMethod)(int);
testMethod = ^(int value){
if (value > 0) {
NSLog(@"current value = %d",value);
testMethod(value - 1);
}
};
testMethod(10);
});
}
}
打印結(jié)果可想可知,雜亂無章。我們想讓有規(guī)律的打印
1.用NSLock加鎖
如果我們這樣加鎖
testMethod = ^(int value){
[lock lock];
if (value > 0) {
NSLog(@"current value = %d",value);
testMethod(value - 1);
}
[lock unlock];
};
我們只能得到打印10,這是為什么呢?通過分析我們一直在層層加鎖,而沒有解鎖,
我們修改加鎖方式
[lock lock];
testMethod(10);
[lock unlock];
但是這種會出現(xiàn)堵塞,因?yàn)橹挥忻看窝h(huán)完從10到1再第一次循環(huán)。
2.我們用NSRecursiveLock加鎖
for (int i= 0; i<100; i++) {
dispatch_async(dispatch_get_global_queue(0, 0), ^{
static void (^testMethod)(int);
[recursiveLock lock];
testMethod = ^(int value){
if (value > 0) {
NSLog(@"current value = %d",value);
testMethod(value - 1);
}
[recursiveLock unlock];
};
testMethod(10);
});
}
打印正常
NSLock底層實(shí)現(xiàn)
NSLock是Foundation的類,由于OC的Foundation沒有開源,我們看swift源碼。
NSLock遵循NSLocking協(xié)議
public protocol NSLocking {
func lock()
func unlock()
}
NSLock底層封裝了pthread_mutex所以NSLcok是互斥鎖
NSLock的lock:實(shí)際上是對pthread_mutex進(jìn)行鎖操作。
NSLock的unlock:對pthread_mutex解鎖并進(jìn)行廣播。
NSRecursiveLock的底層實(shí)現(xiàn)
NSRecursiveLock的實(shí)現(xiàn)和NSLock大致相同,只是在隨pthread_mutex初始化的時候設(shè)置了遞歸參數(shù)
pthread_mutexattr_init(attrs)
pthread_mutexattr_settype(attrs, Int32(PTHREAD_MUTEX_RECURSIVE))
pthread_mutex_init(mutex, attrs)
NSCondition使用和底層實(shí)現(xiàn)
NSCondition使用
NSCondition的使用是在賣燒餅,當(dāng)有燒餅時才會賣給顧客,如果沒有燒餅,顧客要等一會。如果沒有顧客,店主也會做。
- (void)lg_testConditon{
_testCondition = [[NSCondition alloc] init];
//創(chuàng)建生產(chǎn)-消費(fèi)者
for (int i = 0; i < 50; i++) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
[self lg_producer];
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
[self lg_consumer];
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
[self lg_consumer];
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
[self lg_producer];
});
}
}
- (void)lg_producer{
[_testCondition lock];
self.ticketCount = self.ticketCount + 1;
NSLog(@"生產(chǎn)一個 現(xiàn)有 count %zd",self.ticketCount);
[_testCondition signal];
[_testCondition unlock];
}
- (void)lg_consumer{
// 線程安全
[_testCondition lock];
if (self.ticketCount == 0) {
NSLog(@"等待 count %zd",self.ticketCount);
// 保證正常流程
[_testCondition wait];
}
self.ticketCount -= 1;
NSLog(@"消費(fèi)一個 還剩 count %zd ",self.ticketCount);
[_testCondition unlock];
}
NSCondition的底層實(shí)現(xiàn)
NSCondition是對pthread_mutex和pthread_cond的封裝
lock和unlock是對pthread_mutex的操作。
wait和signal是對pthread_cond的wait和signal操作。
broadcast對pthread_cond_broadcast,對cond進(jìn)行signal,喚醒所有等待的線程
NSCondition 的對象實(shí)際上作為一個鎖和一個線程檢查器:鎖主要 為了當(dāng)檢測條件時保護(hù)數(shù)據(jù)源,執(zhí)行條件引發(fā)的任務(wù);線程檢查器 主要是根據(jù)條件決定是否繼續(xù)運(yùn)行線程,即線程是否被阻塞
1:[condition lock];//一般用于多線程同時訪問、修改同一個數(shù)據(jù)源,保證在同一 時間內(nèi)數(shù)據(jù)源只被訪問、修改一次,其他線程的命令需要在lock 外等待,只到 unlock ,才可訪問
2:[condition unlock];//與lock 同時使用
3:[condition wait];//讓當(dāng)前線程處于等待狀態(tài)
4:[condition signal];//CPU發(fā)信號告訴線程不用在等待,可以繼續(xù)執(zhí)行
NSConditionLock
NSConditionLock的底層是對NSCondition的封裝
1.1 NSConditionLock 是鎖,一旦一個線程獲得鎖,其他線程一定等待
1.2 [xxxx lock]; 表示 xxx 期待獲得鎖,如果沒有其他線程獲得鎖(不需要判斷內(nèi)部的 condition) 那它能執(zhí)行此行以下代碼,如果已經(jīng)有其他線程獲得鎖(可能是條件鎖,或者無條件 鎖),則等待,直至其他線程解鎖
1.3 [xxx lockWhenCondition:A條件]; 表示如果沒有其他線程獲得該鎖,但是該鎖內(nèi)部的 condition不等于A條件,它依然不能獲得鎖,仍然等待。如果內(nèi)部的condition等于A條件,并且 沒有其他線程獲得該鎖,則進(jìn)入代碼區(qū),同時設(shè)置它獲得該鎖,其他任何線程都將等待它代碼的 完成,直至它解鎖。
1.4 [xxx unlockWithCondition:A條件]; 表示釋放鎖,同時把內(nèi)部的condition設(shè)置為A條件
1.5 return = [xxx lockWhenCondition:A條件 beforeDate:A時間]; 表示如果被鎖定(沒獲得 鎖),并超過該時間則不再阻塞線程。但是注意:返回的值是NO,它沒有改變鎖的狀態(tài),這個函 數(shù)的目的在于可以實(shí)現(xiàn)兩種狀態(tài)下的處理
1.6 所謂的condition就是整數(shù),內(nèi)部通過整數(shù)比較條件
NSConditionLock總結(jié)
線程 1 調(diào)用[NSConditionLock lockWhenCondition:],此時此刻因?yàn)椴粷M足當(dāng)前條件,所以會進(jìn)入 waiting 狀態(tài),當(dāng)前進(jìn)入到 waiting 時,會釋放當(dāng)前的互斥鎖。
此時當(dāng)前的線程 3 調(diào)用[NSConditionLock lock:],本質(zhì)上是調(diào)用 [NSConditionLock
lockBeforeDate:],這里不需要比對條件值,所以線程 3 會打印
接下來線程 2 執(zhí)行[NSConditionLock lockWhenCondition:],因?yàn)闈M足條件值,所以線程
2 會打印,打印完成后會調(diào)用[NSConditionLock unlockWithCondition:],這個時候講
value 設(shè)置為 1,并發(fā)送 boradcast, 此時線程 1 接收到當(dāng)前的信號,喚醒執(zhí)行并打印。
自此當(dāng)前打印為 線程 3->線程 2 -> 線程 1。
[NSConditionLock lockWhenCondition:]:這里會根據(jù)傳入的 condition 值和 Value 值進(jìn)行對比,如果不相等,這里就會阻塞,進(jìn)入線程池,否則的話就繼續(xù)代碼執(zhí)行
[NSConditionLock unlockWithCondition:]: 這里會先更改當(dāng)前的 value 值,然后進(jìn)行廣播,喚醒當(dāng)前的線程