NSThread for concurrent operation

126 Views Asked by At

add 1000 elements (say integer elements) to an array using 4 NSThread. if adding an objects takes 1 unit of time, then adding 1000 objects will take 1000 unit of time. By using 4 threads I want to reduce it to 250 units. How to achieve this using NSThreads. Thanks

1

There are 1 best solutions below

0
CRD On

Short answer: You can't achieve this using NSThread (or GCD)

Longer answer: The Objective-C NSArray type is not thread-safe and does not support concurrent updating. While you can wrap an NSArray in a thread-safe wrapper so it can be safely updated by more than one thread such a wrapper would achieve that by serialising the updates – so you don't save any time (and actually spend some in that thread safe wrapper).

Maybe you meant something different: If it is not the adding of items to an array which you wish to overlap but instead the generation of those items prior to adding then you can do that with NSThread or GCD provided you also wrap the NSArray in a thread-safe wrapper.

The current recommended way to do concurrent operations is to use GCD, aka Dispatch. If you read up on that you will find how to make an array thread-safe using a serial queue and barrier operations, and how to run your 4 tasks using a concurrent queue.

HTH