在Grand Central Dispatch中使用dispatch_sync [英] using dispatch_sync in Grand Central Dispatch

查看:146
本文介绍了在Grand Central Dispatch中使用dispatch_sync的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以用真正明确的用例来解释 dispatch_sync GCD 中的目的是什么?我不明白在哪里,为什么我必须使用这个。

Can anyone explain with really clear use cases what the purpose of dispatch_sync in GCD is for? I can't understand where and why I would have to use this.

谢谢!

推荐答案

当你想要执行一个块并等待结果时,你使用它。

You use it when you want to execute a block and wait for the results.

一个例子是你使用的模式一个分派队列而不是锁同步。例如,假设您有一个共享的NSMutableArray a ,访问由调度队列 q 调解。后台线程可能会附加到数组(async),而你的前台线程正在拉取第一个项目(同步):

One example of this is the pattern where you're using a dispatch queue instead of locks for synchronization. For example, assume you have a shared NSMutableArray a, with access mediated by dispatch queue q. A background thread might be appending to the array (async), while your foreground thread is pulling the first item off (synchronously):

NSMutableArray *a = [[NSMutableArray alloc] init];
// All access to `a` is via this dispatch queue!
dispatch_queue_t q = dispatch_queue_create("com.foo.samplequeue", NULL);

dispatch_async(q, ^{ [a addObject:something]; }); // append to array, non-blocking

__block Something *first = nil;            // "__block" to make results from block available
dispatch_sync(q, ^{                        // note that these 3 statements...
        if ([a count] > 0) {               // ...are all executed together...
             first = [a objectAtIndex:0];  // ...as part of a single block...
             [a removeObjectAtIndex:0];    // ...to ensure consistent results
        }
});

这篇关于在Grand Central Dispatch中使用dispatch_sync的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆