Frizlab
Frizlab

Reputation: 909

Is copying an NSMutableArray thread-safe?

Let's say I have a mutable array containing some objects in the variable array.

Let's say from thread A I do:

NSArray *arrayCopy = [array copy];

and from thread B:

[array addObject:NSNull.null];

Is it safe? Specifically, can this code crash because of a potential modification of array while it is being copied?

Upvotes: 1

Views: 944

Answers (2)

Artyom Razinov
Artyom Razinov

Reputation: 301

Apple says that NSMutableArray is not thread-safe. However if you add objects in one thread and copy in other, it won't crash. If you add object from different threads, it would crash.

import Foundation
import XCPlayground

var array = NSMutableArray()
var queues = [NSOperationQueue]()

let syncQueue = NSOperationQueue()
syncQueue.maxConcurrentOperationCount = 1

for i in 0..<100 {
    let queue = NSOperationQueue()
    queue.maxConcurrentOperationCount = 1
    queues.append(queue)

    queue.addOperationWithBlock({
        for j in 0..<100000 {
            if j == 0 {
                sleep(1)
            } else {
                usleep(j < 5 ? 100 : rand() % 10 == 0 ? 1 : 0)
            }

            if i % 2 == 0 {
                syncQueue.addOperationWithBlock({
                    array.addObject(NSNumber(int: rand()))
                })
            } else {
                var copy = array.copy()
            }
        }
    })
}

XCPSetExecutionShouldContinueIndefinitely()

However, I didn't find documentation, where it will be described (that copy function is thread safe on NSMutableArray). If someone provides a link, I'll appreciate.

Upvotes: 1

Related Questions