【问题标题】:What code is written behind waitUntilAllOperationsAreFinished (NSOperationQueue)?waitUntilAllOperationsAreFinished(NSOperationQueue)后面写了什么代码?
【发布时间】:2026-02-21 17:10:02
【问题描述】:

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/NSOperationQueue_class/Reference/Reference.html#//apple_ref/occ/instm/NSOperationQueue/waitUntilAllOperationsAreFinished上对这个方法的描述说:

当被调用时,这个方法会阻塞当前线程并等待接收者的当前和排队的操作完成执行。当当前线程被阻塞时,接收器继续启动已经排队的操作并监视那些正在执行的操作。在此期间,当前线程无法向队列添加操作,但其他线程可以。一旦所有挂起的操作都完成了,这个方法就会返回。

我想知道 waitUntilAllOperationsAreFinished 背后的代码是什么,它允许这种行为(阻塞当前线程,接收器继续......)?我有兴趣编写产生类似行为的代码,因此我会感谢任何以类似方式表现的等效代码(是的,Apple 对我来说是黑盒)。

更具体地说:NSOperationQueue 如何进行线程阻塞,同时允许接收器处理其内容(我的猜测:在运行 currentRunLoop 时调度信号量)?

谢谢!

【问题讨论】:

    标签: objective-c ios nsoperationqueue


    【解决方案1】:

    正如你所说,实现是未知的。但它很容易实现这种行为:

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

    _dispatchOperation 反过来会阻塞由队列管理的工作线程触发的信号量。当其中一个发出信号时,它将从其队列中分派下一个操作。

    【讨论】:

      【解决方案2】:

      无意中,我发现了这个:How to implement an NSRunLoop inside an NSOperation,处理与我在这里提出的完全相同的问题:“那么如何在不锁定主线程的情况下完成与 waitUntilFinished:YES 相同的行为?” em>

      与我的另一个 SO 主题配对:"Block" main thread (dispatch_get_main_queue()) and (or not) run currentRunLoop periodically - what is the difference?,它回答了我的问题。

      后期更新:有趣的源代码也与我的问题部分相关:https://github.com/gnustep/gnustep-base/blob/master/Source/NSOperation.m

      【讨论】: