有人能解释一下dispatch_sync和dispatch_async之间的区别吗?

时间:2013-09-10 12:22:40

标签: iphone ios

当我使用不同的任务在同一队列上调用dispatch_async方法两次时,它会在不同的线程上执行任务,而不是同一个线程执行任务。

void(^myBlock)(void) = ^{
  for(int i = 0;i < 10 ; i++)
  {
     NSLog(@"%d and current queue = %@",i,[NSThread currentThread]);   
  }
};

-(void)viewDidLoad   
{
    [super viewDidLoad];
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_
    DEFAULT, 0);

    dispatch_async(queue,myBlock);    
    dispatch_async(queue,myBlock);
}

当我运行这个程序时,它会创建两个线程。以下是输出。

2013-09-10 17:45:20.435 ConcurrencyDemo [1331:30b] 0和当前队列= {name =(null),num = 3}
2013-09-10 17:45:20.435 ConcurrencyDemo [1331:1603] 0和当前队列= {name =(null),num = 2}
2013-09-10 17:45:20.438 ConcurrencyDemo [1331:1603] 1和当前队列= {name =(null),num = 2}
2013-09-10 17:45:20.438 ConcurrencyDemo [1331:30b] 1和当前队列= {name =(null),num = 3}
2013-09-10 17:45:20.440 ConcurrencyDemo [1331:1603] 2和当前队列= {name =(null),num = 2}
2013-09-10 17:45:20.440 ConcurrencyDemo [1331:30b] 2和当前队列= {name =(null),num = 3}
2013-09-10 17:45:20.441 ConcurrencyDemo [1331:1603] 3和当前队列= {name =(null),num = 2}
2013-09-10 17:45:20.441 ConcurrencyDemo [1331:30b] 3和当前队列= {name =(null),num = 3}
2013-09-10 17:45:20.442 ConcurrencyDemo [1331:30b] 4和当前队列= {name =(null),num = 3}
2013-09-10 17:45:20.442 ConcurrencyDemo [1331:1603] 4和当前队列= {name =(null),num = 2}
2013-09-10 17:45:20.443 ConcurrencyDemo [1331:1603] 5和当前队列= {name =(null),num = 2}
2013-09-10 17:45:20.443 ConcurrencyDemo [1331:30b] 5和当前队列= {name =(null),num = 3}
2013-09-10 17:45:20.444 ConcurrencyDemo [1331:30b] 6和当前队列= {name =(null),num = 3}
2013-09-10 17:45:20.444 ConcurrencyDemo [1331:1603] 6和当前队列= {name =(null),num = 2}
2013-09-10 17:45:20.445 ConcurrencyDemo [1331:30b] 7和当前队列= {name =(null),num = 3}
2013-09-10 17:45:20.445 ConcurrencyDemo [1331:1603] 7和当前队列= {name =(null),num = 2}
2013-09-10 17:45:20.446 ConcurrencyDemo [1331:1603] 8和当前队列= {name =(null),num = 2}
2013-09-10 17:45:20.446 ConcurrencyDemo [1331:30b] 8和当前队列= {name =(null),num = 3}
2013-09-10 17:45:20.448 ConcurrencyDemo [1331:30b] 9和当前队列= {name =(null),num = 3}
2013-09-10 17:45:20.448 ConcurrencyDemo [1331:1603] 9和当前队列= {name =(null),num = 2}

谁能告诉我为什么会这样?

1 个答案:

答案 0 :(得分:4)

将调度块分配给线程是内部实现细节。您可能不会依赖系统使用任何特定线程,主队列除外,它总是在主线程上运行。

然而,在这种特殊情况下,这种线程情况正是您应该期待的。除主队列之外的全局队列是并发队列。因此,您应该期望系统创建足够的线程,以便在硬件限制内同时有效地为您放置的所有块提供服务。你期望发生什么?

对于您的具体问题,dispatch_async表示“将此块放在队列中并立即返回”。 dispatch_sync表示“将此块放在队列中,等待它运行,然后返回。”