不再使用鎖(Lock)
用戶隊(duì)列可以用于替代鎖來(lái)完成同步機(jī)制。在傳統(tǒng)多線程編程中,你可能有一個(gè)對(duì)象要被多個(gè)線程使用,你需要一個(gè)鎖來(lái)保護(hù)這個(gè)對(duì)象:
NSLock *lock;
訪問(wèn)代碼會(huì)像這樣:
- (id)something
{
id localSomething;
[lock lock];
localSomething = [[something retain] autorelease];
[lock unlock];
return localSomething;
}
- (void)setSomething:(id)newSomething
{
[lock lock];
if(newSomething != something)
{
[something release];
something = [newSomething retain];
[self updateSomethingCaches];
}
[lock unlock];
}
使用GCD,可以使用queue來(lái)替代:
dispatch_queue_t queue;
要用于同步機(jī)制,queue必須是一個(gè)用戶隊(duì)列,而非全局隊(duì)列,所以使用usingdispatch_queue_create初始化一個(gè)。然后可以用dispatch_barrier_async和dispatch_sync將共享數(shù)據(jù)的訪問(wèn)代碼封裝起來(lái):
- (id)something
{
__block id localSomething;
dispatch_sync(queue, ^{
localSomething = [something retain];
});
return [localSomething autorelease];
}
- (void)setSomething:(id)newSomething
{
dispatch_barrier_async(queue, ^{
if(newSomething != something)
{
[something release];
something = [newSomething retain];
[self updateSomethingCaches];
}
});
}