为什么要用 dispatch_sync

本文探讨了在Grand Central Dispatch中如何利用dispatch_sync和dispatch_async实现同步与异步操作,通过实例展示了如何在主线程和后台线程间进行资源共享与互斥操作,确保数据一致性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自:http://stackoverflow.com/questions/4607125/using-dispatch-sync-in-grand-central-dispatch


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

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
        }
});
share | improve this answer
 
 
I'll +1 this, since it's technically correct, although I there isn't much value in doing a single dispatch_async followed by a dispatch_sync on the same queue. However this same pattern is useful when you want to spawn multiple concurrent jobs on another queue and then wait for them all. –  kperryua Jan 5 '11 at 19:57
 
Thanks. This is beginning to make sense. What if I want to start multiple concurrent threads using dispatch_apply that access a single resource with mutual exclusion. How do I do this with GCD? Is the only way is to use a dispatch_async with serial queue within my dispatch_apply? Is there a way to use dispatch_sync? –  Rasputin Jones Jan 5 '11 at 20:56
 
@kperryua - sorry if the example wasn't clear - the idea is that the a separate thread would be doing multiple dispatch_async's to the queue –  David Gelhar Jan 6 '11 at 1:20
 
@David Gelhar - No problem. Just making mention for others who come looking. –  kperryua Jan 6 '11 at 6:01
5 
I also like to think of it as being similar to using -performSelector:onThread:withObject:waitUntilDone: or performSelectorOnMainThread:withObject:waitUntilDone: and setting waitUntilDone to YES. –  Brad Larson Jan 6 '11 at 18:42
show 3 more comments

First understand its brother dispatch_async

//Do something
dispatch_async(queue, ^{
    //Do something else
});
//Do More Stuff

You use dispatch_async to create a new thread. When you do that, the current thread will not stop. That means //Do More Stuff may be executed before //Do something else finish

What happens if you want the current thread to stop?

You do not use dispatch at all. Just write the code normally

//Do something
//Do something else
//Do More Stuff

Now, say you want to do something on a DIFFERENT thread and yet wait as if and ensure that stuffs are done consecutively.

There are many reason to do this. UI update, for example, is done on main thread.

That's where you use dispatch_sync

//Do something
dispatch_sync(queue, ^{
    //Do something else
});
//Do More Stuff

Here you got //Do something //Do something else and //Do More stuff done consecutively even though //Do something else is done on a different thread.

Usually, when people use different thread, the whole purpose is so that something can get executed without waiting. Say you want to download large amount of data but you want to keep the UI smooth.

Hence, dispatch_sync is rarely used. But it's there. I personally never used that. Why not ask for some sample code or project that does use dispatch_sync.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值