首页 > 解决方案 > NSOperationQueue、异步任务和 maxConcurrentOperationCount

问题描述

我正在编写一些特定于网络的多线程代码。我已经有 dispatch_group 特定的示例工作。但是我遇到了 NSOperationQueue 并想尝试一下。

在高层次上,我的伪代码如下所示:

  1. 我初始化 NSOperationQueue 并将 maxConcurrentOperationCount 设置为某个有限数 (5)
  2. 我将一个并发队列与这个 NSOperationQueue 相关联。
  3. 然后我开始将 NSOperationBlocks 添加到这个队列中。该语法如下所示:
{ 
    for (NSURL url in allUrls) {
        NSBlockOperation *jtOperation = [NSBlockOperation blockOperationWithBlock:^{
           [kick network download for url which is blocking in nature]) 
        }];
        [operationBlockQueue addOperation:jtOperation];
    }

//wait here till all urls are downloaded.
//Keep printing [operationQueue operationCount] after every 30 seconds 

//and url download code looks like: 
1. Initialize NSURLSession. 
2. Add NSDataTask to it. 
3. Wait till callbacks return. (success or error) (using blocking dispatch_semaphore)
4. After success/failure return.   
}

我希望创建的线程数只有 5。但我可以看到并发线程数为 200。我怀疑这一切都归结为同步/异步块。但是我仍然很困惑,因为我的代码块被阻塞了。

我还尝试了一个简单的练习:

    int var = 2;
    dispatch_queue_t browseQueue = dispatch_queue_create("com.myqueue.msdbrowse", DISPATCH_QUEUE_CONCURRENT);
    NSOperationQueue *myOpQueue = [[NSOperationQueue alloc]init];
    [myOpQueue setMaxConcurrentOperationCount:5];
    [myOpQueue setUnderlyingQueue:browseQueue];
    for (i=0; i<25; i++) {
        [myOpQueue addOperationWithBlock:^{
            NSLog(@"value of i is %d",i);
            while (var != 3) {

            }
        }];
    }

     while(1) {
         NSLog(@"total concurrent queues are:%d",[myOpQueue operationCount]);
         sleep(5);
     }
and here output was total concurrent queues are 25. 

标签: iosobjective-cobjective-c-blocks

解决方案


推荐阅读