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 <stdio.h>
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 on Ars Technica mentioned how Clang (a new compiler) was way more awesome at compiler warnings. Thanks to a tweet 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 <stdio.h>
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
So the only thing left to do was to set one of our closures up to run in one of the GCD queues.
#include <dispatch/dispatch.h>
#include <stdio.h>
#include <time.h>
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.
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.