-1

当我使用不同的任务在同一个队列上调用 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}

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

4

1 回答 1

4

将分派的块分配给线程是一个内部实现细节。您可能不依赖于使用任何特定线程的系统,除了主队列,它将始终在主线程上运行。

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

对于您的具体问题,dispatch_async意思是“将此块放入队列并立即返回”。dispatch_sync意思是“把这个块放在队列中,等待它运行,然后返回。”

于 2013-09-10T12:35:04.227 回答