【问题标题】:Setting concurrent operation for NSOperationQueue causes only that number of operation为 NSOperationQueue 设置并发操作只会导致该数量的操作
【发布时间】:2013-05-21 13:44:02
【问题描述】:

我有一个 NSOperationQueue,里面有 NSOperation 对象

NSOperationQueue *aQueue = [[ NSOperationQueue alloc ] init];
[aQueue setMaxConcurrentOperationCount:3];

for (int index=0; index<=5; index++) {
    MYOperation *anOperation = [[MYOperation alloc] init];//MYOperation subclass from NSOperation
    [aQueue addOperation:anOperation];
}
NSLog(@"Number of Operations:%d",[aQueue operationCount]);//It gives 5 count

队列一次只允许执行 3 个操作(根据定义)。 当我尝试添加第 4 个操作时,它会添加到队列中,但该操作从未执行并被丢弃。

问题:为什么队列丢弃操作的次数多于其并发值?

【问题讨论】:

  • @MikePollard,为什么队列丢弃的操作多于它的并发值?
  • 以下是类文档中的内容:The NSOperation class is an abstract class you use to encapsulate the code and data associated with a single task。您不能直接使用NSOperation 类,您必须覆盖它并设置一些它将运行的操作。
  • 第四次操作被丢弃的证据在哪里?第五个和第六个有什么关系?
  • 如果可能,还显示MyOperation 的来源,并确保操作完成(如果它们是并发的,则在它们完成时设置isFinished,否则它们将保留阻塞队列)。

标签: iphone ios multithreading nsoperation nsoperationqueue


【解决方案1】:

NSOperationQueue 管理一个线程在后台执行提交的操作。 (从 10.6 开始使用 Grand Central Dispatch)。默认情况下,提交的操作在辅助线程上执行。
您在提交一批操作后立即查询操作队列 - 此时队列可能尚未开始执行操作,因此正确报告总操作计数为 6。
如果在查询队列之前添加一些延迟,它可能已经完成所有操作并报告计数为 0。

示例代码:

NSOperationQueue *aQueue = [[ NSOperationQueue alloc ] init];
[aQueue setMaxConcurrentOperationCount:3];

for (int index=0; index<=5; index++) {
    MYOperation *anOperation = [[MYOperation alloc] init];//MYOperation subclass from NSOperation
    [aQueue addOperation:anOperation];
}

double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    NSLog(@"Number of Operations:%d",[aQueue operationCount]);//It gives 5 count
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-15
    • 2018-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-23
    相关资源
    最近更新 更多