iOS - Concurrent access to memory resources
Asked Answered
F

2

5

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?

Ferriter answered 15/6, 2012 at 16:9 Comment(0)
V
1

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.

Verdun answered 15/6, 2012 at 16:37 Comment(1)
Yes, I am using NSURLConnection. Let's imagine we have a for-cycle on a mutable array, what does it happen if another task (connection succeeded) tries to add an object at the end of the array, while the for cycle is executing? Could you please make a brief example of reentrant code in this case?Ferriter
K
1

You may want to look into Grand Central Dispatch's (GCD) and barrier blocks. Barrier blocks will allow you to do what y oh want in the background and "lock" resources.

Check out the Apple documentation and Mike Ash's blog post here on GCD.

The basic gist is that you use a concurrent queue that you create to perform the reads and use a barrier block to block all access to that resource for writing. good stuff.

Good luck

Tim

Kotto answered 15/6, 2012 at 16:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.