Created
March 23, 2011 19:46
-
-
Save alloy/883804 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
% 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