Skip to content

Instantly share code, notes, and snippets.

@nevyn
Created September 6, 2009 21:50
Show Gist options
  • Save nevyn/182010 to your computer and use it in GitHub Desktop.
Save nevyn/182010 to your computer and use it in GitHub Desktop.
#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