DesperateLearner
DesperateLearner

Reputation: 1175

Making an Array threadsafe for various functions - iOS

I have a NSMutableArray *testArray which is accessed by multiple threads and used in 4 different functions. Lets say Class A updates this testArray from thread 13 (background thread) inside function 'addValue:' and Class B updates the testArray from thread 1 (Main thread) inside function 'checkIndex:'.

Inside 'addValue:' function I'm updating the contents of testArray followed by the class B which checks for index of an object in testArray using 'checkIndex'. Class A updates the testArray and Class B fetches the index from the old copy of testArray. Where do I make the testArray thread safe?

For TestArray

 Class A -> addValue:   (BackgroundThread)
 Class B -> checkIndex: (Main Thread)

Upvotes: 0

Views: 118

Answers (1)

Duncan C
Duncan C

Reputation: 131426

Arrays are not thread-safe.

I guess you could create a custom subclass of NSArray (Actually NSMutableArray) that is thread safe, but NSArray is part of a class cluster, and subclassing a class cluster is tricky, and you may have decreased performance because the system uses various internal subclasses to optimize performance based on your use-case, and your subclass likely won't have those smarts.

What you CAN do is to create wrapper functions that ARE thread-safe. Create a class that contains an array and promotes the same accessor methods that NSMutableArray does.

Have that subclass assert a lock around every read or write call to the array.

In this case a spin lock is probably a good choice, as the read and number of collisions is probably fairly small and the speed of your read and write operations should be fast. (A spin lock doesn't require kernel calls, and causes the calling thread to block until another thread's lock is released. The lack of kernel calls means it is very fast in the non-collision case, and since read and write calls are fast, even the collision case isn't that bad.)

Do a search in the Xcode docs for "Thread Programming Guide" for more information about the different types of locks you can use and their pros and cons.

Upvotes: 1

Related Questions