dispatch_semaphore_t這個是使用GCD幫我們進行控制加解鎖控制的方式,當資源很緊張的時候阶女,就要可以使用的,但是也是可以使用鎖控制的哩治,這個看個人習慣秃踩。首先,看看這個dispatch_semaphore_t的創(chuàng)建业筏,降低信號量憔杨,增加信號量。
dispatch_semaphore_create//創(chuàng)建信號量蒜胖,傳入的值必須大于等于0消别,不然會返回NULL。
dispatch_semaphore_wait//等待信號量台谢,減少信號量的值寻狂。
dispatch_semaphore_signal//增加信號量的值。
下面就使用demo講解一下:
@interface dispatchSemaphore()
{
? ? dispatch_semaphore_t semaphore;
}
@end
@implementationdispatchSemaphore
- (instancetype)init{
? ? self= [superinit];
? ? if(self) {
? ? ? ? semaphore = dispatch_semaphore_create(0);
? ? ? ? [self createThread];
? ? }
? ? return self;
}
- (void)createThread{
? ? dispatch_semaphore_signal(semaphore);
? ? dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
? ? dispatch_async(queue, ^{
? ? ? ? dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
? ? ? ? NSLog(@"queue1--begin");
? ? ? ? sleep(1);
? ? ? ? NSLog(@"queue1--end");
? ? ? ? dispatch_semaphore_signal(semaphore);
? ? });
? ? dispatch_async(queue, ^{
? ? ? ? dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
? ? ? ? NSLog(@"queue2--begin");
? ? ? ? sleep(1);
? ? ? ? NSLog(@"queue2--end");
? ? ? ? dispatch_semaphore_signal(semaphore);
? ? });
? ? dispatch_async(queue, ^{
? ? ? ? dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
? ? ? ? NSLog(@"queue3--begin");
? ? ? ? sleep(1);
? ? ? ? NSLog(@"queue3--end");
? ? ? ? dispatch_semaphore_signal(semaphore);
? ? });
}
當dispatch_semaphore_create(0)的時候朋沮,此時一直處于等待狀態(tài)蛇券,必須dispatch_semaphore_signal(semaphore);后,才能執(zhí)行下面的狀態(tài)樊拓,執(zhí)行的順序是依次執(zhí)行怀读。
當dispatch_semaphore_create(1)的時候,就不需要dispatch_semaphore_signal(semaphore);然后就是順序依次執(zhí)行骑脱。
當dispatch_semaphore_create(2)的時候菜枷,就先執(zhí)行1和2兩個任務,當1執(zhí)行完后叁丧,正好3進入GCD中啤誊,相當于一個隊列,1號出隊列拥娄,3號入隊列蚊锹,繼續(xù)執(zhí)行2,然后執(zhí)行3稚瘾。
當dispatch_semaphore_create(3)的時候牡昆,就是并發(fā)執(zhí)行,執(zhí)行順序:
2018-06-13 16:35:56.024268+0800 RunTime[4440:206226] queue2--begin
2018-06-13 16:35:56.024268+0800 RunTime[4440:206225] queue1--begin
2018-06-13 16:35:56.024268+0800 RunTime[4440:206227] queue3--begin
2018-06-13 16:35:57.024913+0800 RunTime[4440:206226] queue2--end
2018-06-13 16:35:57.024915+0800 RunTime[4440:206225] queue1--end
2018-06-13 16:35:57.024927+0800 RunTime[4440:206227] queue3--end
順序不是依次執(zhí)行的。
dispatch_semaphore_wait中第二個參數(shù)丢烘,可以是DISPATCH_TIME_FOREVER或者DISPATCH_TIME_NOW柱宦。
DISPATCH_TIME_NOW//當前
DISPATCH_TIME_FOREVER//未來
也可以使用dispatch_time函數(shù)進行創(chuàng)建,例如:dispatch_time(DISPATCH_TIME_NOW, 50*NSEC_PER_MSEC)
注意:主要控制dispatch_semaphore_create中數(shù)字播瞳,才能進行進行是否并發(fā)掸刊。
當創(chuàng)建dispatch_semaphore_create中數(shù)字大于0的時候,在創(chuàng)建完成后赢乓,dispatch_semaphore_signal(semaphore);調(diào)用后忧侧,也會進行并發(fā)操作,所以牌芋,不一定非要創(chuàng)建時候的數(shù)字和dispatch_async異步的相等蚓炬,也是可以模擬并發(fā)操作的。