Skip to content

Instantly share code, notes, and snippets.

@aquarius
Created November 28, 2011 10:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aquarius/1399872 to your computer and use it in GitHub Desktop.
Save aquarius/1399872 to your computer and use it in GitHub Desktop.
What is the best way to get notified when all callbacks have returned?
for (myObject in objects) {
[myObject doWithCallback: ^(BOOL success){
//
}];
}
@aquarius
Copy link
Author

@steipete
Copy link

can you elaborate a bit more on the problem? I guess the callbacks spin of a new thread? You could consider a NSOperationQueue and listen to the case where it's empty again.

@steipete
Copy link

How do you listen to the "queue empty" event on a gdc queue?

@anlumo
Copy link

anlumo commented Nov 28, 2011

__block NSUInteger counter = 0;
NSUInteger max = [objects count];

dispatch_queue_t q = dispatch_queue_create("com.mindnode.fafnerqueue", DISPATCH_QUEUE_SERIAL);

for (myObject in objects) {
    [myObject doWithCallback: ^(BOOL success){
        dispatch_async(q, ^{
            if(++counter >= max) {
                // Done!
                dispatch_release(q);
            }
    }];
}

@anlumo
Copy link

anlumo commented Nov 28, 2011

Alternative (probably more efficient):

__block volatile int64_t counter = 0;
int64_t max = (int64_t)[objects count];

for (myObject in objects) {
    [myObject doWithCallback: ^(BOOL success){
        if(OSAtomicIncrement64Barrier(&counter) >= max) {
            // Done! Will only be executed once.
        }
    }];
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment