0

The description of this method on https://developer.apple.com/library/mac/documentation/Cocoa/Reference/NSOperationQueue_class/Reference/Reference.html#//apple_ref/occ/instm/NSOperationQueue/waitUntilAllOperationsAreFinished says:

When called, this method blocks the current thread and waits for the receiver’s current and queued operations to finish executing. While the current thread is blocked, the receiver continues to launch already queued operations and monitor those that are executing. During this time, the current thread cannot add operations to the queue, but other threads may. Once all of the pending operations are finished, this method returns.

I wonder what is the code behind waitUntilAllOperationsAreFinished that allows such behavior (blocks current thread, receiver continues...)? I am interested in writing a code producing similar behavior, so I will be thankful for any equivalent (yeah, Apple is black boxed for me) code behaving in a similar way.

More specifically: how NSOperationQueue does its thread blocking, at the same time allowing receiver to work on its stuff (my guess: dispatch semaphores while running currentRunLoop)?

Thanks!

Stanislav Pankevich
  • 11,044
  • 8
  • 69
  • 129

2 Answers2

2

As you said, the implementation is unknown. But its easy to achieve the behavior:

- (void)waitUntilAllOperationsAreFinished
{
    while(self.operationCount != 0)
        [self _dispatchOperation];
}

_dispatchOperation in turn would block on a semaphore triggered by the worker threads managed by the queue. When one of them signals it would dispatch the next operation from its queue.

Nikolai Ruhe
  • 81,520
  • 17
  • 180
  • 200
1

Accidentally, I found this: How to implement an NSRunLoop inside an NSOperation, dealing with exactly the same question that I asked here: "So how do I accomplish the same behavior as waitUntilFinished:YES without locking up the main thread?"

Got in pair with my another SO topic: "Block" main thread (dispatch_get_main_queue()) and (or not) run currentRunLoop periodically - what is the difference?, it answers my question.

LATER UPDATE: interesting source code which is also partly related to my question: https://github.com/gnustep/gnustep-base/blob/master/Source/NSOperation.m

Community
  • 1
  • 1
Stanislav Pankevich
  • 11,044
  • 8
  • 69
  • 129