NSOperationQueue,异步任务和maxConcurrentOperationCount

时间:2019-01-29 02:46:09

标签: ios objective-c objective-c-blocks

我正在编写一些特定于网络的多线程代码。我已经有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. 

0 个答案:

没有答案