Grand Central Dispatch + Clang == Awesome
=========================================
Blocks
------
I read about blocks in 10.6 and they sounded quite cool. So the first thing I
did (after poking at the new Expose) was to try and write a block:
So I started with this:
#include
int
main(int argc, char* argv[])
{
fprintf(stderr, "Creating a closure!\n");
int x = ^{ printf("hello world\n"); };
x();
}
Obviously the int 'x = ^{}' syntax was wrong, but I was banking on compiler
warnings to give me a hint:
davisp@cube:~/tests/gcd$ gcc -o gcd first.c
first.c: In function 'main':
first.c:7: error: incompatible types in initialization
first.c:8: error: called object 'x' is not a function
Doh! No love. But then an epiphany. The review [1] on Ars Technica
mentioned how Clang (a new compiler) was way more awesome at compiler warnings.
Thanks to a tweet [2] the other day I took it for a spin:
davisp@cube:~/tests/gcd$ /Developer/usr/bin/clang -o gcd first.c
first.c:7:13: error: incompatible type initializing 'void (^)(void)', expected
'int'
int x = ^{ printf("hello world\n"); };
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 diagnostic generated.
Whoa neato! So make the suggested update:
#include
int
main(int argc, char* argv[])
{
fprintf(stderr, "Creating a closure!\n");
void (^x)(void) = ^{ printf("hello world\n"); };
x();
}
And compile and run:
davisp@cube:~/tests/gcd$ /Developer/usr/bin/clang -o gcd first.c
davisp@cube:~/tests/gcd$ ./gcd
Creating a closure!
hello world
Grand Central Dispatch
----------------------
So the only thing left to do was to set one of our closures up to run in one of
the GCD queues.
#include
#include
#include
int
main(int argc, char* argv[])
{
fprintf(stderr, "DO IT!\n");
dispatch_apply(10, dispatch_get_global_queue(0, 0), ^(size_t i){
fprintf(stderr, "I: %d\n", i);
});
sleep(1);
}
And try that on for size:
davisp@cube:~/tests/gcd$ /Developer/usr/bin/clang -o gcd first.c
davisp@cube:~/tests/gcd$ ./gcd
DO IT!
I: 0
I: 1
I: 2
I: 3
I: 4
I: 5
I: 6
I: 7
I: 8
I: 9
I think me and GCD are going to be very good friends.
One Thought
-----------
So far I'm quite fond of GCD. It looks to be as easy to use as was advertised.
The only thing that worries me is if I start using this for lots of code, I'm
locked to OS X. Some of the scientific bits wouldn't even be worth sketching out
without an implementation for Linux.
I know its only a matter of time, but I haven't the slightest how long that
will be.
References
----------
[1]: http://arstechnica.com/apple/reviews/2009/08/mac-os-x-10-6.ars/9#llvm-clang
[2]: http://twitter.com/binary42/statuses/3689493854
Copyright Notice
----------------
Copyright 2008-2010 Paul Joseph Davis
License
-------
http://creativecommons.org/licenses/by/3.0/