Created
September 6, 2009 21:50
-
-
Save nevyn/182010 to your computer and use it in GitHub Desktop.
This file contains 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
#include <stdio.h> | |
#include <pthread.h> | |
#include <Foundation/Foundation.h> | |
typedef void (^LockedResourceWorker)(void *resource); | |
typedef void (^LockedResourceAcquirer)(LockedResourceWorker worker); | |
LockedResourceAcquirer LockedResource(void *resource) | |
{ | |
NSLock *lock = [[NSLock new] autorelease]; | |
return Block_copy(^(LockedResourceWorker worker) { | |
[lock lock]; | |
worker(resource); | |
[lock unlock]; | |
}); | |
} | |
struct something_s { | |
LockedResourceAcquirer locked_buffer; | |
}; | |
void doingSomething(struct something_s something, int i); | |
int main (int argc, const char * argv[]) { | |
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; | |
struct something_s something; | |
int *resource = malloc(sizeof(int)); | |
something.locked_buffer = LockedResource(resource); | |
dispatch_apply(10, dispatch_get_global_queue(0, 0), ^(size_t i){doingSomething(something, i);}); | |
something.locked_buffer(^ (void *buffer) { | |
printf("Buffer should be 45: %d", *((int*)buffer)); | |
}); | |
Block_release(something.locked_buffer); | |
[pool drain]; | |
return 0; | |
} | |
void doingSomething(struct something_s something, int i) | |
{ | |
something.locked_buffer(^ (void *buffer) { | |
*((int*)buffer) += i; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment