1.同步 异步
dispatch_async(queue, ^{});
dispatch _sync(queue, ^{});(不要在主线程使用,容易死锁)
2.串行 并行
dispatch_queue_t serialQueue = dispatch_queue_create("com.sensology.serial1",DISPATCH_QUEUE_SERIAL);
dispatch_queue_t concurQueue = dispatch_queue_create("com.sensology.concur",DISPATCH_QUEUE_CONCURRENT);
3.种类
主线程 : Main Dispatch Queue 串行 dispatch_get_main_queue();
全局线程: Global Dispatch Queue 并行 dispatch_get_global_queue(PRIORITY,0);
(1) High Priority 高
(2) Default Priority 默认
(3) Low Priority 低
(4) Background Priority 后台
4.优先级
dispatch_set_target_queue(queue,PRIORITY);
5.延迟
dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW,3ULL*NSEC_PER_SEC);
dispatch_after(time,dispatch_get_main_queue(),^{});
执行时间 3S~3S+1个RunLoop时间(1/60S)
ULL (unsigned long long)
NSEC_PER_SEC 秒
6.组
控制多个并行线程执行完毕后再去操作,dispatch_group_create();
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group,queue,^{});
dispatch_group_async(group,queue,^{});
dispatch_group_async(group,queue,^{});
dispatch_group_async(group,queue,^{});
dispatch_group_notify(group,dispatch_get_main_queue(),^{});
//dispatch_group_wait(group,DISPATCH_TIME_FOREVER) 也可以用等待
7.栅栏
可以用来控制线程的读与写,dispatch_barrier_async()
dispatch_async(queue,reading);
dispatch_async(queue,reading);
dispatch_async(queue,reading);
dispatch_barrier_async(queue,writing);
dispatch_async(queue,reading);
dispatch_async(queue,reading);
dispatch_async(queue,reading);
8.diapatch_apply
将时间按指定的次数追加到队列中,可处理数组
dispatch_apply(10,queue,^(size_t index){
});
9.挂起与恢复
挂起不执行,恢复继续执行
dispatch_suspend(queue);
dispatch_resume(queue);
10.信号
计数为0时等待,大于等于1时减去1,去执行;
dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);//初始值为1
for (int i = 0;i < 1000; i++ ) {
dispatch_async(queue.^{
dispatch_semphore_wait(semaphore,DISPATCH_TIME_FOREVER);//信号来之前,一直等待 ;计数-1;
NSlog(@"%d",i);
dispatch_semaphore_signal(semphore);//事件完成后,计数+1;
});
}
11.一次
可用在初始化,确保只执行一次;
static dispatch_once_t pred;
dispatch_once(&pred,^{
//初始化
}
);
12.读取文件
多线程分段读取文件;
Dispatch I/O, Dispatch Data
pipe_q = dispatch_queue_create("PipeQ", NULL);//
pipe_channel = dispatch_io_create(DISPATCH_IO_STREAM, fd, pipe_q, ^(int err){//生成Dispatch I/O,发生错误时,执行BLOCK
close(fd);
});
*out_fd = fdpair[1];
dispatch_io_set_low_water(pipe_channel, SIZE_MAX);//一次读取的大小
dispatch_io_read(pipe_channel, 0, SIZE_MAX, pipe_q, ^(bool done, dispatch_data_t pipedata, int err){//并行读取
if (err == 0)
{
size_t len = dispatch_data_get_size(pipedata);
if (len > 0)
{
const char *bytes = NULL;
char *encoded;
uint32_t eval;
dispatch_data_t md = dispatch_data_create_map(pipedata, (const void **)&bytes, &len);
encoded = asl_core_encode_buffer(bytes, len);
asl_msg_set_key_val(aux, ASL_KEY_AUX_DATA, encoded);
free(encoded);
eval = _asl_evaluate_send(NULL, (aslmsg)aux, -1);
_asl_send_message(NULL, eval, aux, NULL);
asl_msg_release(aux);
dispatch_release(md);
}
}
if (done)
{
dispatch_semaphore_signal(sem);
dispatch_release(pipe_channel);
dispatch_release(pipe_q);
}
});
13.Dispatch_source
dispatch_source 可以取消 dispatch_queue 不能取消