iOS-并发访问内存资源 [英] iOS - Concurrent access to memory resources

查看:75
本文介绍了iOS-并发访问内存资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序从服务器,数据和数据描述符下载了一些资源.这些下载是由用户操作触发的,可以同时执行,也就是说,一次最多可以进行50次下载.所有这些异步任务最终都会在内存中创建对象(例如,将叶子附加到数据结构中,例如将键添加到可变字典中或将对象添加到数组中).我的问题是:这会引起稳定性问题吗?例如,如果多个同时执行的任务试图将键添加到同一词典中,那么我应该处理这种情况,并放置某种锁吗?如果我实现了一个for循环,该循环在阵列中查找图形元素,那么其他正在运行的任务是否有可能在循环期间改变阵列的内容?除了官方文档以外,关于此多任务,多线程问题有任何参考或主要的一般性指导吗?

解决方案

取决于您如何处理下载-如果您使用的是NSURLConnection,它将为您和您的代码处理单独的线程/并发是可重入的,因此您不必担心同时执行操作. 如果创建自己的线程,则可能会遇到问题.

您的代码在主线程(主运行循环)中运行,可以说您有一个NSURLConnection也正在运行,然后它将在单独的线程中运行.但是,处理连接过程中发生的事件的委托代码在运行循环中运行,而不是在其他线程中运行.这意味着您的代码一次只能执行一件事.成功的连接方法不会与您的任何其他代码同时被称为 .如果您有一个for循环正在运行,则它将阻塞您的主线程,直到完成循环为止;与此同时,如果在for循环仍在运行时完成连接,则直到循环结束后,您的委托代码才会执行​​.

My app downloads several resources from server, data and data descriptors. These downloads, triggered by user actions, can be performed simultaneously, let's say, up to 50 downloads at a time. All these asynchronous tasks end up creating objects in memory, (e.g. appending leaves to data structures, such as adding keys to mutable dictionaries or objects to arrays). My question is: can this cause stability issues? For instance, if several simultaneous tasks try to add keys to the same dictionary, am I supposed to handle the situation, placing some kind of locks? If I implement a for cycle which looks for graphical elements in an array, is it possible that other running tasks might change the array content 'during' the cycle? Any reference or major, general orientation about this multitasking, multithreading issues other than official documentation?

解决方案

Depends how you are dealing with the downloads - if you are using NSURLConnection it handles the separate threading / concurrency for you and your code is reentrant thus you don't have to worry about simultaneous action. If you are creating your own threads you potentially have issues.

EDIT: Your code runs in a main thread (the main run loop), lets say you have an NSURLConnection that is also running then it will run in a separate thread. However your delegate code that deals with events that happen while the connection is in progress runs in your run loop, not in the other thread. This means your code can only ever execute one thing at a time. A connection succeeded method would not get called at the same time as any of your other code. If you had a for loop running then it would block your main thread until it has finished looping, in the meanwhile if the connection finished while the for loop is still running then your delegate code will not execute until after the loop has finished.

这篇关于iOS-并发访问内存资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆