dispatch_semaphore主要應(yīng)用有:
(1)線程同步(同步任務(wù))
(2)線程加鎖(資源訪問(wèn)控制)
相關(guān)函數(shù)有以下三個(gè):
(1)dispatch_semaphore_create
(2)dispatch_semaphore_signal
(3)dispatch_semaphore_wait
下面將逐一介紹:
(1)dispatch_semaphore_t
dispatch_semaphore_create(intptr_t value):創(chuàng)建信號(hào)量唆涝,接收一個(gè)long類型的參數(shù), 返回一個(gè)dispatch_semaphore_t類型的信號(hào)量炬转,值為傳入的參數(shù)哆姻。注意:傳入的value須大于或等于0,否則dispatch_semaphore_create會(huì)返回NULL优质;
(2)intptr_t dispatch_semaphore_signal(dispatch_semaphore_t dsema):發(fā)送信號(hào),并使信號(hào)量+1乙帮;
(3)intptr_t dispatch_semaphore_wait(dispatch_semaphore_t dsema, dispatch_time_t timeout):等待信號(hào)量扑媚,若信號(hào)量小于0,則會(huì)等待埃篓,阻塞當(dāng)前線程处坪,直到信號(hào)量大于0或者超時(shí),若信號(hào)量大于0架专,則會(huì)使信號(hào)量減1同窘,繼續(xù)向下執(zhí)行。
關(guān)于信號(hào)量部脚,借用別人停車場(chǎng)的例子:
停車場(chǎng)剩余4個(gè)車位想邦,那么即使同時(shí)來(lái)了四輛車也能停得下。如果此時(shí)來(lái)了五輛車委刘,那么就有一輛需要等待丧没。信號(hào)量的值就相當(dāng)于剩余車位的數(shù)目鹰椒,dispatch_semaphore_wait函數(shù)就相當(dāng)于來(lái)了一輛車,dispatch_semaphore_signal就相當(dāng)于走了一輛車呕童。停車位的剩余數(shù)目在初始化的時(shí)候就已經(jīng)指明了(dispatch_semaphore_create(value:Int)))漆际,調(diào)用一次dispatch_semaphore_signal,剩余的車位就增加一個(gè)拉庵;調(diào)用一次dispatch_semaphore_wait剩余車位就減少一個(gè)灿椅;當(dāng)剩余車位為0時(shí),再來(lái)車(即調(diào)用dispatch_semaphore_wait)就只能等待钞支。有可能同時(shí)有幾輛車等待一個(gè)停車位茫蛹。有些車主,沒(méi)有耐心烁挟,給自己設(shè)定了一段等待時(shí)間婴洼,這段時(shí)間內(nèi)等不到停車位就走了,如果等到了就開(kāi)進(jìn)去停車撼嗓。而有些車主就想把車停在這柬采,所以就一直等下去。
代碼示例:
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);//創(chuàng)建信號(hào)量
__block int sum = 0;
int delta = 3;
for (int i = 0; i < 100; i++) {
dispatch_async(queue, ^{
// 等待信號(hào)量(加鎖)
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
sum += delta;
NSLog(@"sum = %d semaphore = %@", sum, semaphore);
// 發(fā)送信號(hào)量(解鎖)
dispatch_semaphore_signal(semaphore);
});
}