在 Grand Central Dispatch 中使用 dispatch_sync [英] using dispatch_sync in Grand Central Dispatch
问题描述
谁能用非常清晰的用例来解释 GCD
中 dispatch_sync
的目的是什么?我不明白我在哪里以及为什么必须使用它.
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
介导.后台线程可能会附加到数组(异步),而您的前台线程正在拉出第一项(同步):
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屋!