dispatch_sync編程
dispatch_async函數的」async」意味着非同步,就是將指定的Block非同步的追加到指定的Dispatch Queue中,disptch_async函數不作任何等待;相對應的」sync」意味着同步,也就是說將指定的Block同步追加到Dispatch Queue中,在追加Block結束前,dispatch_sync函數會一直等待多線程
應用情景:執行Main Dispatch Queue時,使用另外的線程Global Dispatch Queue進行處理,處理結束後當即使用所獲得的結果app
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)async
dispatch_sync(queue,^{/*處理*/});函數
注意:死鎖問題spa
dispatch_queue_t queue = dispatch_get_main_queue()線程
dispatch_sync(queue,^{NSLog(@"Hello ?")});get
dispatch_queue_t queue = dispatch_queue_create("com,example.gcd.MySerialDispachQueue", NULL);同步
dispatch_async(queue,^{it
dispatch_sync(queue, ^{
NSLog(@"hello");
})
});
dispatch_apply
該函數按指定的次數將指定的Block追加到指定的Dispatch Queue中,並等待所有處理執行結束
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_apply(10, queue, ^(size_t index) {
NSLog(@"%zu",index);
});
NSLog(@"done");
dispatch_suspend/dispatch_resume
當追加大量處理到Dispatch Queue時,在追加處理的過程當中,有時但願不執行已追加的處理,這時只要掛起Dispatch Queue,當能夠執行時再恢復
//掛起
dispatch_suspend(queue);
//恢復
dispatch_resume(queue);
Dispatch Semaphore
是持有計數的信號,該計數是多線程編程中的計數類型信號。計數值爲0時等待,計數爲1或大於1時,減去1而不等待
//create
dispatch_semaphore_t semaphore =dispatch_semaphore_create(1);
//持有
dispatch_retain(semaphore);
//釋放
dispatch_release(semaphore);
//阻塞等待
dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, 1ull*NSEC_PER_SEC);
long result = dispatch_semaphore_wait(semaphore, time);
if (result == 0) {
/*計數值大於0*/
}else{
/*等待time時間後,計數值仍然爲0*/
}
在等待時間內,接收到single消息 dispatch_semaphore_wait當即返回
dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
NSMutableArray *array = [[NSMutableArray alloc]init];
for (int i = 0; i < 1000; i++) {
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
[array addObject:[NSNumber numberWithInt:i]];
dispatch_semaphore_signal(semaphore);
}
dispatch_release(semaphore);
dispatch_once
dispatch_once函數是保證在應用程序執行中只執行一次指定處理的API
static dispatch_once_t pred;
dispatch_once(&pred,^{
/*初始化*/
});
單例模式:
+ (AnObject *)sharedSnashotRecordsMgr
{
static AnObject *_sharedInstance = nil;
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
_sharedInstance = [[AnObject alloc] init];
});
return _sharedInstance;
}