

Grand Central Dispatch: The Sleeping Barber Problem - koenbok
http://www.madebysofa.com/#blog/the_sleeping_barber

======
vilya
The code in the linked article has a bug: it doesn't wait for the queued tasks
to complete, so the program will exit while people are still waiting for their
haircuts - or worse, while the barber's actually cutting some hair.

You can fix this by using dispatch_group_async instead of dispatch_async, then
after the loop (before releasing the queue) call dispatch_group_wait to make
sure all the queued blocks have completed.

This plus creating and releasing the group only adds three lines of code; the
rest of the author's algorithm is correct as far I can tell.

I guess it just goes to show that even with Grand Central you still have to be
a little careful.

~~~
jonathandann
No, you're right, except that the while-loop condition is YES, so it never
exits! It's worth noting that all threads in Cocoa (and GCD) are detached
pthreads, so whatever you do you have to wait on critical operations.

The sample code is technically correct, but your argument is also valid. I was
going for a demo of something that applies in the larger scope of real-world
apps :)

GCD, by no stretch of the imagination, negates the requirement of thought!

------
vinutheraj
Here's a good discussion on a related topic in the 9fans archive -
<http://www.mail-archive.com/9fans@9fans.net/msg10581.html>

~~~
gchpaco
That thread was full of knee jerk reactions and deficient in sound reasoning
for a good while. I think Roman Shaposhnik had the best point when he noted
that you could do something like Cilk (not exactly the same, but similar) as a
library if C had closures, instead of as a new language supersetting C. It's
not like block scoped functions are in any way new or unusual; even gcc has
had downward funargs (which aren't enough to do GCD with, FWIW) for years.

The thing is, Objective C is the main way to develop Cocoa applications.
Blocks, garbage collection, and a number of other features that have been
roundly whined about are ways of increasing the expressivity of the language
so that it is more comfortable to write applications in. One can argue that C
is a miserable applications development language (and I think you'd be right)
but unfortunately we have relatively few other options. Apple used to have a
Java-Cocoa bridge that has been deprecated for some time because nobody cared.

~~~
randrews
I've found Rubycocoa to be really easy to use, and it's supported by Apple. It
might go the way of the Java bridge in the future, though.

~~~
tlrobinson
MacRuby seems to be the new hotness for Ruby + Cocoa. Have you tried it? If
so, how does it compare to RubyCocoa?

~~~
durin42
I just saw an absolutely fantastic talk at C4 about MacRuby. It'll be tons
faster than RubyCocoa, because there's no bridging, and it compiles to native
code. You can even do AOT compilation and distribute a native binary!

