我在ios中学习并发编程主题。我为多个串行调度队列做了一个示例应用程序。
-(IBAction)SerialDispatchAction:(id)sender
{
s1queue = dispatch_queue_create( "com.newtok.firstQueue" , NULL);
s2queue = dispatch_queue_create( "com.newtok.secondQueue" , NULL);
dispatch_async(s1queue, ^{
int i=0;
while(i<5)
{
printf("First Asynchronous Dispatch Queue.....\n");
sleep(1);
i++;
}
});
dispatch_async(s2queue, ^{
int i=0;
while(i<5)
{
printf("Second Asynchronous Dispatch Queue.....\n");
sleep(1);
i++;
}
});
dispatch_sync(s1queue ,^{
int i=0;
while(i<5)
{
printf("First Synchronous Dispatch Queue.....\n");
sleep(1);
i++;
}
});
dispatch_sync(s2queue ,^{
int i=0;
while(i<5)
{
printf("Second Synchronous Dispatch Queue.....\n");
sleep(1);
i++;
}
});
}
我读过,如果要创建多个Dispatch串行队列,队列将同时运行。我得到了这样的出局....
First Asynchronous Dispatch Queue.....
Second Asynchronous Dispatch Queue.....
First Asynchronous Dispatch Queue.....
Second Asynchronous Dispatch Queue.....
First Asynchronous Dispatch Queue.....
Second Asynchronous Dispatch Queue.....
First Asynchronous Dispatch Queue.....
Second Asynchronous Dispatch Queue.....
First Asynchronous Dispatch Queue.....
Second Asynchronous Dispatch Queue.....
First Synchronous Dispatch Queue.....
First Synchronous Dispatch Queue.....
First Synchronous Dispatch Queue.....
First Synchronous Dispatch Queue.....
First Synchronous Dispatch Queue.....
Second Synchronous Dispatch Queue.....
Second Synchronous Dispatch Queue.....
Second Synchronous Dispatch Queue.....
Second Synchronous Dispatch Queue.....
Second Synchronous Dispatch Queue.....
dispatch_async和dispatch_sync有什么区别? 它如何相互倾斜?
答案 0 :(得分:1)
dispatch_sync()阻止并确保队列中的所有项目在返回之前已完成运行。 dispatch_async()只需提交块并立即返回。然后块同时或串行运行取决于您已将工作提交到哪种队列。正如您所推测的那样,多个串行队列将相互并发运行(而不是并发运行的队列中的各个块,因为它们将使用并发队列)。
答案 1 :(得分:0)
dispatch_sync
将阻止线程直到完成,dispatch_async
提交块并发运行。我建议你重新阅读GCD上的苹果文档和this article。
答案 2 :(得分:0)
如果打印出[NSThread currentThread],您可能会理解dispatch_sync有时会优化以在当前线程上运行 - 而不是多个线程。在您的示例中,dispatch_sync在契约中的主线程上运行,因此您会发现结果是序列化的。