It’s my first Grand Central Dispatch code but it doesn’t work. Working on Mac OS X 10.8 and last Xcode version. I know it’s too basic. Thanks.
#import <Foundation/Foundation.h>
#import <dispatch/dispatch.h>
void printResult(int r);
void printResult(int r)
{
NSLog(@"%i", r);
}
int main(int argc, const char * argv[])
{
@autoreleasepool {
dispatch_queue_t queue = dispatch_queue_create("myQueue", NULL);
dispatch_async(queue, ^{
int number = pow(2, 5);
dispatch_async(dispatch_get_main_queue(), ^{
printResult(number);
});
});
}
return 0;
}
First. Your application actually exits before the blocks you passed in GCD could finish.
To fix that, you could use GCD groups and synchronization tools that they give you.
Second. Here you will encounter another problem called deadlock. The Second block is added to the main thread queue. And main thread is actually waiting for this block to finish, so it could not be executed. Add the second block to the queue you’ve created before.
Now you can see
32in console, which is what you expect.