void dispatch_sync( dispatch_queue_t queue, dispatch_block_t block);
dispatch_sync_的定义如上所示,将block添加到queue中,无论queue是并行队列仍是串行队列,block的执行知足FIFO须要等待先进入queue中的block执行完以后才能被执行,在同一个queue中同一时刻只能有一个block执行。并发
//建立一个并行队列 dispatch_queue_t queue2 = dispatch_queue_create("concurrent.dispatch.queue", DISPATCH_QUEUE_CONCURRENT); dispatch_sync(queue2, ^{ NSLog(@"step0"); }); //建立一个串行队列 dispatch_queue_t queue1 = dispatch_queue_create("serial.dispatch.queue", DISPATCH_QUEUE_SERIAL); dispatch_sync(queue1, ^{ NSLog(@"step1"); }); dispatch_sync(queue1, ^{ NSLog(@"step2"); });
程序的输出结果:spa
step0
step1
step2
若是queue是一个并行队列,理论上并行队列中的block应该并行,可是经过实验验证,queue中的block是串行执行的,为何?难道是我理解错了线程
dispatch_queue_t concurrentQueue = dispatch_queue_create("concurrent.dispatch.queue", DISPATCH_QUEUE_CONCURRENT); dispatch_sync(concurrentQueue, ^{ NSLog(@"step1"); }); dispatch_sync(concurrentQueue, ^{ NSLog(@"step2"); });
程序输出结果:3d
step1
step2
由此能够得出结论,对于并发队列而言,若是做为参数传入到dispatchsync中,那queue中的block是串行执行的,根据深刻理解dispatchsync中的描述,在调用dispatchsync时,在底层是对queue进行了加锁,在一个block执行完以后才能取其余的block来执行。这样就不可以发挥出并行队列的并发执行的价值。code
写这篇博客时仍是有一个没有理解到的问题,既然dispatchsync是串行执行,而且要阻塞当前线程,那么直接在当前线程中执行block的代码就能够了,那么dispatchsync就没有存在的意义了,这点没有想明白,why?blog
参考资料:队列
http://zhangbuhuai.com/2015/04/11/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3dispatch_sync/get