Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS - Concurrent access to memory resources

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?

like image 768
user236739 Avatar asked Nov 03 '22 22:11

user236739


2 Answers

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.

like image 138
Gruntcakes Avatar answered Nov 08 '22 12:11

Gruntcakes


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

like image 37
timthetoolman Avatar answered Nov 08 '22 13:11

timthetoolman