On Apr 25, 2014, at 1:11 AM, Jonathan Taylor <jonathan.tay...@glasgow.ac.uk> 
wrote:

> Have you looked at the output from System Trace on both systems? I often find 
> that to be informative.

OK, I tried this and it did turn out to be very informative :) even though I 
don’t know how to interpret any of the numbers. But just the pretty charts 
alone told the story:
- With @synchronized there was very little activity in the System Calls or 
Scheduling tracks.
- With GCD there was a whole ton of activity.
I was surprised there’s this much of a difference, because there’s no actual 
concurrency in the code at this point! In the commit I’ve rolled back to, all 
I’ve done is taken my existing single-threaded code and wrapped the C calls 
with either @synchronized or dispatch_sync. My understanding is that while 
dispatch_sync is technically switching to a different dispatch queue, if there 
isn’t any contention it will just do some bookkeeping and run the block on the 
same thread’s stack. So in this case I wouldn’t expect there to be any actual 
thread switching going on; except there is.

… So then I searched the project for “dispatch_async” and found that there was 
actually _one_ call to it, so my statement about “no actual concurrency” above 
was a lie. The block it runs doesn’t really need to be async; I was just 
running it that way because I didn’t need it to complete right away. I changed 
that call to dispatch_sync, and voila! Almost all the thread scheduling and 
system calls went away; the system trace now looks like the @synchronized one, 
and the benchmark times are now slightly better than @synchronized!

I guess this makes sense: dispatch_sync is super cheap in the uncontended case, 
but if there’s a dispatch_async pending, then that one obviously has to run 
first, and it’s probably been scheduled onto another thread, so the 
dispatch_sync has to either queue onto that thread or at least do some 
more-expensive locking to wait for the other thread to finish the async call.

I’m ending up at the opposite of the received wisdom, namely:
* dispatch_sync is a lot cheaper than dispatch_async
* only use dispatch_async if you really need to, or for an expensive operation, 
because it will slow down all your dispatch_sync calls

I wish there were a big fat super-dense O’Reilly or Big Nerd Ranch book about 
GCD so I didn’t have to figure all this out on my own...

—Jens
_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to