1
votes

I am looking for a pattern to allow for processing of 2 threads (NSOperations) at the same time, and only return once both are complete. To complicate this, I need a queue of these dual operations.

So, my thought was to have a NSOperation that contains a NSOperationQueue to handle both. Then the NSOperation queue would perform both at the same time, alert me when the queue is empty, and we can go on our way.

Looking for thoughts around this, or a better way to do this task/pitfalls of the above.

Thanks in advance!

Rob

1

1 Answers

1
votes

You can use NSOperation's dependency support to deal with this. Basically you create a third operation that runs the code that you want to run when the first two operations are complete, then add the first two operations as dependencies to the third operation and add them all to a queue:

NSOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
    NSLog(@"op1!");
}];

NSOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
    NSLog(@"op2!");
}];

NSOperation *completionOp = [NSBlockOperation blockOperationWithBlock:^{
    NSLog(@"op1 and op2 are complete!");
}];

[completionOp addDependency:op1];
[completionOp addDependency:op2];

NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperation:completionOp];
[queue addOperation:op1];
[queue addOperation:op2];

Which outputs:

op1!
op2!
op1 and op2 are complete!

Note that, even though completionBlock is added to the queue first, it's run last because of the dependencies it has on op1 and op2.