ios - NSOperationQueue、异步任务和 maxConcurrentOperationCount
问题描述
我正在编写一些特定于网络的多线程代码。我已经有 dispatch_group 特定的示例工作。但是我遇到了 NSOperationQueue 并想尝试一下。
在高层次上,我的伪代码如下所示:
- 我初始化 NSOperationQueue 并将 maxConcurrentOperationCount 设置为某个有限数 (5)
- 我将一个并发队列与这个 NSOperationQueue 相关联。
- 然后我开始将 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.
解决方案
推荐阅读
- python - AWS Lambda:无法导入模块“包/文件”:没有名为“util”的模块
- json - 如何使用 python 将 JSON 数据转换为 .tsv 文件。
- jquery - 通过使用 jQuery.ajax() 发出请求,从 URL 中检索 Json 数组
- python - 来自 CME 的 Webscrape 表格,包括从下拉菜单中选择所需的表格
- java - ObjectMapper 不接受来自 HttpURLConnection 的 JSON 响应
- java - Java BorderLayout.add 每次都不起作用
- jquery - 我该怎么办: var value = foo(bar); 其中 foo 是一个通过 JSON 请求查找值的函数
- linux - 映射 MMIO 区域回写不起作用
- javascript - 使用 Firebase 从最大到最小列出和排序记录并打印到 HTML 表格正文
- machine-learning - 当因变量具有高自相关性时,最佳预测度量是什么?