Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "break" out of dispatch_apply()?

Is there a way to simulate a break statement in a dispatch_apply() block?

E.g., every Cocoa API I've seen dealing with enumerating blocks has a "stop" parameter:

[array enumerateObjectsUsingBlock:^(id obj, NSUInteger i, BOOL *stop) {
    if ([obj isNotVeryNice]) {
        *stop = YES; // No more enumerating!
    } else {
        NSLog(@"%@ at %zu", obj, i);
    }
}];

Is there something similar for GCD?

like image 266
Michael Avatar asked Jun 23 '10 21:06

Michael


2 Answers

By design, dispatch_*() APIs have no notion of cancellation. The reason for this is because it is almost universally true that your code maintains the concept of when to stop or not and, thus, also supporting that in the dispatch_*() APIs would be redundant (and, with redundancy comes errors).

Thus, if you want to "stop early" or otherwise cancel the pending items in a dispatch queue (regardless of how they were enqueued), you do so by sharing some bit of state with the enqueued blocks that allows you to cancel.

if (is_canceled()) return;

Or:

__block BOOL keepGoing = YES;
dispatch_*(someQueue, ^{
    if (!keepGoing) return;
    if (weAreDoneNow) keepGoing = NO;
}

Note that both enumerateObjectsUsingBlock: and enumerateObjectsWithOptions:usingBlock: both support cancellation because that API is in a different role. The call to the enumeration method is synchronous even if the the actual execution of the enumerating blocks may be fully concurrent depending on options.

Thus, setting the *stopFlag=YES tells the enumeration to stop. It does not, however, guarantee that it will stop immediately in the concurrent case. The enumeration may, in fact, execute a few more already enqueued blocks before stopping.

(One might briefly think that it would be more reasonable to return BOOL to indicate whether the enumeration should continue. Doing so would have required that the enumerating block be executed synchronously, even in the concurrent case, so that the return value could be checked. This would have been vastly less efficient.)

like image 176
bbum Avatar answered Sep 19 '22 03:09

bbum


I don't think dispatch_apply supports this. The best way I can think of to imitate it would be to make a __block boolean variable, and check it at the beginning of the block. If it's set, bail out quickly. You'd still have to run the block through the rest of the iterations, but it would be faster.

like image 43
BJ Homer Avatar answered Sep 21 '22 03:09

BJ Homer