1

我在 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 有什么区别?它是如何相互浸染的?

4

3 回答 3

1

dispatch_sync将阻塞线程直到它完成,dispatch_async提交块以并发运行。我建议您重新阅读 GCD 上的苹果文档和这篇文章

于 2012-02-09T06:58:54.950 回答
1

dispatch_sync() 阻塞并确保队列中的所有项目在返回之前都已完成运行。dispatch_async() 只是提交块并立即返回。然后该块是同时运行还是串行运行取决于您将工作提交到哪种队列。正如您正确推测的那样,多个串行队列将彼此同时运行(与队列上的各个块同时运行相反,因为它们将与并发队列一起运行)。

于 2012-02-10T03:56:38.847 回答
0

如果您打印出 [NSThread currentThread],您可能会理解 dispatch_sync 有时会优化为在当前线程上运行 - 而不是多个线程。在您的示例中, dispatch_sync 实际上在主线程上运行,因此您发现结果是序列化的。

于 2013-09-02T02:31:01.903 回答