Skip to content

Instantly share code, notes, and snippets.

@alloy
Created March 23, 2011 19:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alloy/883804 to your computer and use it in GitHub Desktop.
Save alloy/883804 to your computer and use it in GitHub Desktop.
% cat model.m
#import <Foundation/Foundation.h>
#import <dispatch/dispatch.h>
void Init_model() {};
@interface Model : NSObject {
//int result;
NSString *result;
dispatch_group_t group;
}
@end
@implementation Model
- (id)init {
if (self = [super init]) {
//result = 0;
result = [NSString string];
group = NULL;
}
return self;
}
- (void)dealloc {
if (group != NULL) {
dispatch_release(group);
}
[result release];
[super dealloc];
}
- (void)preloadResult {
group = dispatch_group_create();
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
dispatch_group_async(group, queue, ^{
NSLog(@"Async dispatch!");
sleep(2);
//result = 42;
result = [NSString stringWithString:@"banana!"];
});
}
//- (int)result {
- (NSString *)result {
if (group != NULL) {
NSLog(@"Waiting till preloading finishes...");
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
dispatch_release(group);
group = NULL;
} else {
NSLog(@"Not preloaded!");
sleep(2);
//result = 42;
result = [NSString stringWithString:@"banana!"];
}
return result;
}
@end
// $ gcc -bundle -fobjc-gc -framework Foundation model.m -o model.bundle
// macruby -r model.bundle -e 'm = Model.new.preloadResult; sleep 1; p m.result'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment