轉(zhuǎn)載自:http://www.itdecent.cn/p/938d68ed832c#
一、前言
前段時(shí)間看了幾個(gè)開(kāi)源項(xiàng)目,發(fā)現(xiàn)他們保持線程同步的方式各不相同,有@synchronized、NSLock、dispatch_semaphore、NSCondition、pthread_mutex、OSSpinLock。后來(lái)網(wǎng)上查了一下,發(fā)現(xiàn)他們的實(shí)現(xiàn)機(jī)制各不相同,性能也各不一樣。不好意思,我們平常使用最多的@synchronized是性能最差的。下面我們先分別介紹每個(gè)加鎖方式的使用,在使用一個(gè)案例來(lái)對(duì)他們進(jìn)行性能對(duì)比。
二、介紹與使用
2.1、@synchronized
NSObject *obj = [[NSObject alloc] init];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
????????@synchronized(obj) {
????????????????NSLog(@"需要線程同步的操作1 開(kāi)始");? ? ? ? ? ?
????????????????sleep(3);
????????????????NSLog(@"需要線程同步的操作1 結(jié)束");? ? ? ?
????????????????}? ?
????????});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{? ? ? ?
????????sleep(1);
????????@synchronized(obj) {
????????????????NSLog(@"需要線程同步的操作2");? ? ? ?
????????}? ?
});
@synchronized(obj)指令使用的obj為該鎖的唯一標(biāo)識(shí),只有當(dāng)標(biāo)識(shí)相同時(shí),才為滿足互斥,如果線程2中的@synchronized(obj)改為@synchronized(self),剛線程2就不會(huì)被阻塞,@synchronized指令實(shí)現(xiàn)鎖的優(yōu)點(diǎn)就是我們不需要在代碼中顯式的創(chuàng)建鎖對(duì)象,便可以實(shí)現(xiàn)鎖的機(jī)制,但作為一種預(yù)防措施,@synchronized塊會(huì)隱式的添加一個(gè)異常處理例程來(lái)保護(hù)代碼,該處理例程會(huì)在異常拋出的時(shí)候自動(dòng)的釋放互斥鎖。所以如果不想讓隱式的異常處理例程帶來(lái)額外的開(kāi)銷,你可以考慮使用鎖對(duì)象。
上面結(jié)果的執(zhí)行結(jié)果為:
2016-06-29 20:48:35.747 SafeMultiThread[35945:580107] 需要線程同步的操作1 開(kāi)始
2016-06-29 20:48:38.748 SafeMultiThread[35945:580107] 需要線程同步的操作1 結(jié)束
2016-06-29 20:48:38.749 SafeMultiThread[35945:580118] 需要線程同步的操作2
2.2、dispatch_semaphore
dispatch_semaphore_t signal = dispatch_semaphore_create(1);? ? dispatch_time_t overTime = dispatch_time(DISPATCH_TIME_NOW,3*NSEC_PER_SEC);dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{? ? ? ?
????????dispatch_semaphore_wait(signal, overTime);
????????????????NSLog(@"需要線程同步的操作1 開(kāi)始");
? ? ? ? ? ? ? ? sleep(2);NSLog(@"需要線程同步的操作1 結(jié)束");? ? ?
? ????????dispatch_semaphore_signal(signal);? ?
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{? ? ? ?
????????sleep(1);? ? ? ?
????????dispatch_semaphore_wait(signal, overTime);
????????????????NSLog(@"需要線程同步的操作2");? ? ? ?
????????dispatch_semaphore_signal(signal);? ?
? ? ? });
dispatch_semaphore是GCD用來(lái)同步的一種方式,與他相關(guān)的共有三個(gè)函數(shù),分別是dispatch_semaphore_create,dispatch_semaphore_signal,dispatch_semaphore_wait。
(1)dispatch_semaphore_create的聲明為:
dispatch_semaphore_t? dispatch_semaphore_create(long value);
傳入的參數(shù)為long,輸出一個(gè)dispatch_semaphore_t類型且值為value的信號(hào)量。
值得注意的是,這里的傳入的參數(shù)value必須大于或等于0,否則dispatch_semaphore_create會(huì)返回NULL。
(2)dispatch_semaphore_signal的聲明為:
long dispatch_semaphore_signal(dispatch_semaphore_t dsema)
這個(gè)函數(shù)會(huì)使傳入的信號(hào)量dsema的值加1;
(3) dispatch_semaphore_wait的聲明為:
long dispatch_semaphore_wait(dispatch_semaphore_t dsema, dispatch_time_t timeout);
這個(gè)函數(shù)會(huì)使傳入的信號(hào)量dsema的值減1;這個(gè)函數(shù)的作用是這樣的,如果dsema信號(hào)量的值大于0,該函數(shù)所處線程就繼續(xù)執(zhí)行下面的語(yǔ)句,并且將信號(hào)量的值減1;如果desema的值為0,那么這個(gè)函數(shù)就阻塞當(dāng)前線程等待timeout(注意timeout的類型為dispatch_time_t,不能直接傳入整形或float型數(shù)),如果等待的期間desema的值被dispatch_semaphore_signal函數(shù)加1了,且該函數(shù)(即dispatch_semaphore_wait)所處線程獲得了信號(hào)量,那么就繼續(xù)向下執(zhí)行并將信號(hào)量減1。如果等待期間沒(méi)有獲取到信號(hào)量或者信號(hào)量的值一直為0,那么等到timeout時(shí),其所處線程自動(dòng)執(zhí)行其后語(yǔ)句。
dispatch_semaphore 是信號(hào)量,但當(dāng)信號(hào)總量設(shè)為 1 時(shí)也可以當(dāng)作鎖來(lái)。在沒(méi)有等待情況出現(xiàn)時(shí),它的性能比 pthread_mutex 還要高,但一旦有等待情況出現(xiàn)時(shí),性能就會(huì)下降許多。相對(duì)于 OSSpinLock 來(lái)說(shuō),它的優(yōu)勢(shì)在于等待時(shí)不會(huì)消耗 CPU 資源。
如上的代碼,如果超時(shí)時(shí)間overTime設(shè)置成>2,可完成同步操作。如果overTime<2的話,在線程1還沒(méi)有執(zhí)行完成的情況下,此時(shí)超時(shí)了,將自動(dòng)執(zhí)行下面的代碼。
上面代碼的執(zhí)行結(jié)果為:
2016-06-29 20:47:52.324 SafeMultiThread[35945:579032] 需要線程同步的操作1 開(kāi)始
2016-06-29 20:47:55.325 SafeMultiThread[35945:579032] 需要線程同步的操作1 結(jié)束
2016-06-29 20:47:55.326 SafeMultiThread[35945:579033] 需要線程同步的操作2
如果把超時(shí)時(shí)間設(shè)置為<2s的時(shí)候,執(zhí)行的結(jié)果就是:
2016-06-30 18:53:24.049 SafeMultiThread[30834:434334] 需要線程同步的操作1 開(kāi)始
2016-06-30 18:53:25.554 SafeMultiThread[30834:434332] 需要線程同步的操作2
2016-06-30 18:53:26.054 SafeMultiThread[30834:434334] 需要線程同步的操作1 結(jié)束
2.3、NSLock
NSLock*lock = [[NSLockalloc] init];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{ ?
????????//[lock lock];
????????[lock lockBeforeDate:[NSDatedate]];
????????????????NSLog(@"需要線程同步的操作1 開(kāi)始");? ? ? ?
????????????? ? sleep(2);
????????????????NSLog(@"需要線程同步的操作1 結(jié)束");? ? ? ?
????????[lock unlock];? ? ? ? ? ?
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{? ? ? ?
????????sleep(1);
????????if([lock tryLock]) {//嘗試獲取鎖,如果獲取不到返回NO,不會(huì)阻塞該線程
????????????????NSLog(@"鎖可用的操作");? ? ? ? ? ?
????????????????[lock unlock];? ? ? ?
????????}else{
????????????????NSLog(@"鎖不可用的操作");? ? ? ?
????????}
????????NSDate*date = [[NSDatealloc] initWithTimeIntervalSinceNow:3];
????????if([lock lockBeforeDate:date]) {//嘗試在未來(lái)的3s內(nèi)獲取鎖,并阻塞該線程,如果3s內(nèi)獲取不到恢復(fù)線程, 返回NO,不會(huì)阻塞該線程
????????????????NSLog(@"沒(méi)有超時(shí),獲得鎖");? ? ? ? ? ?
????????????????[lock unlock];? ? ? ?
????????}else{
????????????????NSLog(@"超時(shí),沒(méi)有獲得鎖");? ? ? ?
????????}? ? ? ? ? ?
});
NSLock是Cocoa提供給我們最基本的鎖對(duì)象,這也是我們經(jīng)常所使用的,除lock和unlock方法外,NSLock還提供了tryLock和lockBeforeDate:兩個(gè)方法,前一個(gè)方法會(huì)嘗試加鎖,如果鎖不可用(已經(jīng)被鎖住),剛并不會(huì)阻塞線程,并返回NO。lockBeforeDate:方法會(huì)在所指定Date之前嘗試加鎖,如果在指定時(shí)間之前都不能加鎖,則返回NO。
上面代碼的執(zhí)行結(jié)果為:
2016-06-29 20:45:08.864 SafeMultiThread[35911:575795] 需要線程同步的操作1 開(kāi)始
2016-06-29 20:45:09.869 SafeMultiThread[35911:575781] 鎖不可用的操作
2016-06-29 20:45:10.869 SafeMultiThread[35911:575795] 需要線程同步的操作1 結(jié)束
2016-06-29 20:45:10.870 SafeMultiThread[35911:575781] 沒(méi)有超時(shí),獲得鎖
源碼定義如下:
@protocolNSLocking
- (void)lock;
- (void)unlock;
@end
@interfaceNSLock:NSObject{
@privatevoid*_priv;
}
- (BOOL)tryLock;
- (BOOL)lockBeforeDate:(NSDate*)limit;
@property(nullable,copy)NSString*nameNS_AVAILABLE(10_5,2_0);
@end
2.4、NSRecursiveLock遞歸鎖
//NSLock *lock = [[NSLock alloc] init];
NSRecursiveLock*lock = [[NSRecursiveLockalloc] init];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
????????staticvoid(^RecursiveMethod)(int);? ? ? ? ? ? ? ?
????????RecursiveMethod = ^(intvalue) {? ? ? ? ? ? ? ? ? ? ? ?
????????????????[lock lock];
????????????????if(value >0) {
????????????????????????NSLog(@"value = %d", value);? ? ? ? ? ? ? ?
????????????????????????sleep(1);? ? ? ? ? ? ? ?
????????????????????????RecursiveMethod(value -1);? ? ? ? ? ?
????????????????}? ? ? ? ? ?
????????????????[lock unlock]; ? ? ?
????????};? ? ? ? ? ? ? ?
????????RecursiveMethod(5);? ?
});
NSRecursiveLock實(shí)際上定義的是一個(gè)遞歸鎖,這個(gè)鎖可以被同一線程多次請(qǐng)求,而不會(huì)引起死鎖。這主要是用在循環(huán)或遞歸操作中。
這段代碼是一個(gè)典型的死鎖情況。在我們的線程中,RecursiveMethod是遞歸調(diào)用的。所以每次進(jìn)入這個(gè)block時(shí),都會(huì)去加一次鎖,而從第二次開(kāi)始,由于鎖已經(jīng)被使用了且沒(méi)有解鎖,所以它需要等待鎖被解除,這樣就導(dǎo)致了死鎖,線程被阻塞住了。調(diào)試器中會(huì)輸出如下信息:
2016-06-30 19:08:06.393 SafeMultiThread[30928:449008] value = 5
2016-06-30 19:08:07.399 SafeMultiThread[30928:449008] *** -[NSLock lock]: deadlock ( '(null)')
2016-06-30 19:08:07.399 SafeMultiThread[30928:449008] *** Break on _NSLockError() to debug.
在這種情況下,我們就可以使用NSRecursiveLock。它可以允許同一線程多次加鎖,而不會(huì)造成死鎖。遞歸鎖會(huì)跟蹤它被lock的次數(shù)。每次成功的lock都必須平衡調(diào)用unlock操作。只有所有達(dá)到這種平衡,鎖最后才能被釋放,以供其它線程使用。
如果我們將NSLock代替為NSRecursiveLock,上面代碼則會(huì)正確執(zhí)行。
2016-06-30 19:09:41.414 SafeMultiThread[30949:450684] value = 5
2016-06-30 19:09:42.418 SafeMultiThread[30949:450684] value = 4
2016-06-30 19:09:43.419 SafeMultiThread[30949:450684] value = 3
2016-06-30 19:09:44.424 SafeMultiThread[30949:450684] value = 2
2016-06-30 19:09:45.426 SafeMultiThread[30949:450684] value = 1
如果需要其他功能,源碼定義如下:
@interfaceNSRecursiveLock:NSObject{
@privatevoid*_priv;
}
- (BOOL)tryLock;
- (BOOL)lockBeforeDate:(NSDate*)limit;
@property(nullable,copy)NSString*nameNS_AVAILABLE(10_5,2_0);
@end
2.5、NSConditionLock條件鎖
NSMutableArray*products = [NSMutableArrayarray];
NSIntegerHAS_DATA =1;
NSIntegerNO_DATA =0;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
????????while(1) {? ? ? ? ? ?
????????????????[lock lockWhenCondition:NO_DATA];? ? ? ? ? ?
????????????????[products addObject:[[NSObjectalloc] init]];
????????????????NSLog(@"produce a product,總量:%zi",products.count);? ?
????????? ? ? ? [lock unlockWithCondition:HAS_DATA];? ? ? ? ? ?
????????????????sleep(1);? ? ? ?
????????}? ? ? ? ? ? });
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
????????while(1) {
????????????????NSLog(@"wait for product");? ? ? ? ? ?
????????????????[lock lockWhenCondition:HAS_DATA];? ? ? ? ? ?
????????????????[products removeObjectAtIndex:0];
????????????????NSLog(@"custome a product");? ? ? ? ? ?
????????????????[lock unlockWithCondition:NO_DATA];? ? ? ?
????????}? ? ? ? ? ?
});
當(dāng)我們?cè)谑褂枚嗑€程的時(shí)候,有時(shí)一把只會(huì)lock和unlock的鎖未必就能完全滿足我們的使用。因?yàn)槠胀ǖ逆i只能關(guān)心鎖與不鎖,而不在乎用什么鑰匙才能開(kāi)鎖,而我們?cè)谔幚碣Y源共享的時(shí)候,多數(shù)情況是只有滿足一定條件的情況下才能打開(kāi)這把鎖:
在線程1中的加鎖使用了lock,所以是不需要條件的,所以順利的就鎖住了,但在unlock的使用了一個(gè)整型的條件,它可以開(kāi)啟其它線程中正在等待這把鑰匙的臨界地,而線程2則需要一把被標(biāo)識(shí)為2的鑰匙,所以當(dāng)線程1循環(huán)到最后一次的時(shí)候,才最終打開(kāi)了線程2中的阻塞。但即便如此,NSConditionLock也跟其它的鎖一樣,是需要lock與unlock對(duì)應(yīng)的,只是lock,lockWhenCondition:與unlock,unlockWithCondition:是可以隨意組合的,當(dāng)然這是與你的需求相關(guān)的。
上面代碼執(zhí)行結(jié)果如下:
2016-06-30 20:31:58.699 SafeMultiThread[31282:521698] wait for product
2016-06-30 20:31:58.699 SafeMultiThread[31282:521708] produce a product,總量:1
2016-06-30 20:31:58.700 SafeMultiThread[31282:521698] custome a product
2016-06-30 20:31:58.700 SafeMultiThread[31282:521698] wait for product
2016-06-30 20:31:59.705 SafeMultiThread[31282:521708] produce a product,總量:1
2016-06-30 20:31:59.706 SafeMultiThread[31282:521698] custome a product
2016-06-30 20:31:59.706 SafeMultiThread[31282:521698] wait for product
2016-06-30 20:32:00.707 SafeMultiThread[31282:521708] produce a product,總量:1
2016-06-30 20:32:00.708 SafeMultiThread[31282:521698] custome a product
如果你需要其他功能,源碼定義如下:
@interfaceNSConditionLock:NSObject{
@privatevoid*_priv;
}
- (instancetype)initWithCondition:(NSInteger)conditionNS_DESIGNATED_INITIALIZER;
@property(readonly)NSIntegercondition;
- (void)lockWhenCondition:(NSInteger)condition;
- (BOOL)tryLock;
- (BOOL)tryLockWhenCondition:(NSInteger)condition;
- (void)unlockWithCondition:(NSInteger)condition;
- (BOOL)lockBeforeDate:(NSDate*)limit;
- (BOOL)lockWhenCondition:(NSInteger)condition beforeDate:(NSDate*)limit;
@property(nullable,copy)NSString*nameNS_AVAILABLE(10_5,2_0);
@end
2.6、NSCondition
NSCondition*condition = [[NSConditionalloc] init];
NSMutableArray*products = [NSMutableArrayarray];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
????????while(1) {? ? ? ? ? ?
????????????????[condition lock];
????????????????if([products count] ==0) {
????????????????????????NSLog(@"wait for product");? ? ? ? ? ? ? ?
????????????????????????[condition wait];? ? ? ? ? ?
????????????????}? ? ? ? ? ?
????????????????[products removeObjectAtIndex:0];NSLog(@"custome a product");? ? ? ? ? ?
????????????????[condition unlock];? ? ? ?
????????}? ?
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
????????while(1) {?
????????? ? ? ? ? [condition lock];? ? ? ? ? ?
????????????????[products addObject:[[NSObjectalloc] init]];
????????????????NSLog(@"produce a product,總量:%zi",products.count);? ?
? ? ? ? ? ? ? ? ?[condition signal];? ? ? ? ? ?
????????????????[condition unlock];? ? ? ? ? ?
????????????????sleep(1);? ? ? ?
????????}? ?
});
一種最基本的條件鎖。手動(dòng)控制線程wait和signal。
[condition lock];一般用于多線程同時(shí)訪問(wèn)、修改同一個(gè)數(shù)據(jù)源,保證在同一時(shí)間內(nèi)數(shù)據(jù)源只被訪問(wèn)、修改一次,其他線程的命令需要在lock 外等待,只到unlock ,才可訪問(wèn)
[condition unlock];與lock 同時(shí)使用
[condition wait];讓當(dāng)前線程處于等待狀態(tài)
[condition signal];CPU發(fā)信號(hào)告訴線程不用在等待,可以繼續(xù)執(zhí)行
上面代碼執(zhí)行結(jié)果如下:
2016-06-30 20:21:25.295 SafeMultiThread[31256:513991] wait for product
2016-06-30 20:21:25.296 SafeMultiThread[31256:513994] produce a product,總量:1
2016-06-30 20:21:25.296 SafeMultiThread[31256:513991] custome a product
2016-06-30 20:21:25.297 SafeMultiThread[31256:513991] wait for product
2016-06-30 20:21:26.302 SafeMultiThread[31256:513994] produce a product,總量:1
2016-06-30 20:21:26.302 SafeMultiThread[31256:513991] custome a product
2016-06-30 20:21:26.302 SafeMultiThread[31256:513991] wait for product
2016-06-30 20:21:27.307 SafeMultiThread[31256:513994] produce a product,總量:1
2016-06-30 20:21:27.308 SafeMultiThread[31256:513991] custome a product
2.7、pthread_mutex
__block pthread_mutex_t theLock;? ?
pthread_mutex_init(&theLock,NULL);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{? ? ? ? ? ?
????????pthread_mutex_lock(&theLock);
????????NSLog(@"需要線程同步的操作1 開(kāi)始");? ? ? ? ? ?
????????sleep(3);
????????NSLog(@"需要線程同步的操作1 結(jié)束");? ? ? ? ? ?
????????pthread_mutex_unlock(&theLock);? ? ? ? ? ?
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{? ? ? ? ? ?
????????sleep(1);? ? ? ? ? ?
????????pthread_mutex_lock(&theLock);
????????NSLog(@"需要線程同步的操作2");? ? ? ? ? ?
????????pthread_mutex_unlock(&theLock);? ? ? ? ? ?
});
c語(yǔ)言定義下多線程加鎖方式。
1:pthread_mutex_init(pthread_mutex_t* mutex,const pthread_mutexattr_tattr);
初始化鎖變量mutex。attr為鎖屬性,NULL值為默認(rèn)屬性。
2:pthread_mutex_lock(
pthread_mutex_t*mutex);加鎖
3:pthread_mutex_tylock(
pthread_mutex_t*mutex);加鎖,但是與2不一樣的是當(dāng)鎖已經(jīng)在使用的時(shí)候,返回為EBUSY,而不是掛起等待。
4:pthread_mutex_unlock(
pthread_mutex_t*mutex);釋放鎖
5:pthread_mutex_destroy(
pthread_mutex_t* *mutex);使用完后釋放
代碼執(zhí)行操作結(jié)果如下:
2016-06-30 21:13:32.440 SafeMultiThread[31429:548869] 需要線程同步的操作1 開(kāi)始
2016-06-30 21:13:35.445 SafeMultiThread[31429:548869] 需要線程同步的操作1 結(jié)束
2016-06-30 21:13:35.446 SafeMultiThread[31429:548866] 需要線程同步的操作2
2.8、pthread_mutex(recursive)
__blockpthread_mutex_ttheLock;
//pthread_mutex_init(&theLock, NULL);
pthread_mutexattr_tattr;? ?
pthread_mutexattr_init(&attr);? ?
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);? ?
pthread_mutex_init(&lock, &attr);? ?
pthread_mutexattr_destroy(&attr);? ? ? ?
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
????????staticvoid(^RecursiveMethod)(int);? ? ? ? ? ? ? ?
????????RecursiveMethod = ^(intvalue) {? ? ? ? ? ? ? ? ? ? ? ?
????????????????pthread_mutex_lock(&theLock);if(value >0) {? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
????????????????????????NSLog(@"value = %d", value);? ? ? ? ? ? ? ?
????????????????????????sleep(1);? ? ? ? ? ? ? ?
????????????????????????RecursiveMethod(value -1);? ? ? ? ? ?
????????????????}? ? ? ? ? ?
????????????????pthread_mutex_unlock(&theLock);? ? ? ?
? ? ? ? ? };? ? ? ? ? ? ? ?
????????RecursiveMethod(5);? ?
});
這是pthread_mutex為了防止在遞歸的情況下出現(xiàn)死鎖而出現(xiàn)的遞歸鎖。作用和NSRecursiveLock遞歸鎖類似。
如果使用pthread_mutex_init(&theLock, NULL);初始化鎖的話,上面的代碼會(huì)出現(xiàn)死鎖現(xiàn)象。如果使用遞歸鎖的形式,則沒(méi)有問(wèn)題。
2.9、OSSpinLock
__block OSSpinLock theLock = OS_SPINLOCK_INIT;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{? ?
????????OSSpinLockLock(&theLock);
????????NSLog(@"需要線程同步的操作1 開(kāi)始");? ?
????????sleep(3);
????????NSLog(@"需要線程同步的操作1 結(jié)束");? ?
????????OSSpinLockUnlock(&theLock);? ?
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{? ?
????????OSSpinLockLock(&theLock);? ?
????????sleep(1);
????????NSLog(@"需要線程同步的操作2");? ?
????????OSSpinLockUnlock(&theLock);? ?
});
OSSpinLock 自旋鎖,性能最高的鎖。原理很簡(jiǎn)單,就是一直 do while 忙等。它的缺點(diǎn)是當(dāng)?shù)却龝r(shí)會(huì)消耗大量 CPU 資源,所以它不適用于較長(zhǎng)時(shí)間的任務(wù)。 不過(guò)最近YY大神在自己的博客不再安全的 OSSpinLock中說(shuō)明了OSSpinLock已經(jīng)不再安全,請(qǐng)大家謹(jǐn)慎使用。
三、性能對(duì)比
對(duì)以上各個(gè)鎖進(jìn)行1000000此的加鎖解鎖的空操作時(shí)間如下:
OSSpinLock:? ? ? ? ? ? ? ? ? ? ? ? ? 46.15 ms
dispatch_semaphore:? ? ? ? ? 56.50 ms
pthread_mutex:? ? ? ? ? ? ? ? ? ? 178.28 ms
NSCondition:? ? ? ? ? ? ? ? ? ? ? ? ? 193.38 ms
NSLock:? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 175.02 ms
pthread_mutex(recursive):? 172.56 ms
NSRecursiveLock:? ? ? ? ? ? ? ? ? 157.44 ms
NSConditionLock:? ? ? ? ? ? ? ? ? 490.04 ms
@synchronized:? ? ? ? ? ? ? ? ? ? ? 371.17 ms
總的來(lái)說(shuō):
OSSpinLock和dispatch_semaphore的效率遠(yuǎn)遠(yuǎn)高于其他。
@synchronized和NSConditionLock效率較差。
鑒于OSSpinLock的不安全,所以我們?cè)陂_(kāi)發(fā)中如果考慮性能的話,建議使用dispatch_semaphore。
如果不考慮性能,只是圖個(gè)方便的話,那就使用@synchronized。