IOS深入理解GCD之dispatch_sync

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");
    });

  程序的输出结果:

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");
    });

  程序输出结果:

step1
step2

  由此可以得出结论,对于并发队列而言,如果作为参数传入到dispatchsync中,那queue中的block是串行执行的,根据深入理解dispatchsync中的描述,在调用dispatchsync时,在底层是对queue进行了加锁,在一个block执行完之后才能取其他的block来执行。这样就不能够发挥出并行队列的并发执行的价值。

写这篇博客时还是有一个没有理解到的问题,既然dispatchsync是串行执行,并且要阻塞当前线程,那么直接在当前线程中执行block的代码就可以了,那么dispatchsync就没有存在的意义了,这点没有想明白,why?

 

  参考资料:

http://zhangbuhuai.com/2015/04/11/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3dispatch_sync/

 

原文地址:https://www.cnblogs.com/PerfectSoft/p/5457475.html