Article

Races on Collections and Other APIs

Detects when a thread accesses a mutable object while another thread writes to that object, causing a data race.

Overview

The Thread Sanitizer has been extended to detect unsafe thread accesses of Foundation and Core Foundation framework APIs. This feature applies to the following collection types:

Collection Race with a Mutable Array

In the following example, a mutable array is enumerated in one thread while simultaneously being written to in another thread, without any access synchronization.

let array: NSMutableArray = []
var sum: Int = 0
// Executed on Thread #1
for value in array {
    sum += value as! Int
}
// Executed on Thread #2
array.add(42)

Solution

Use Dispatch APIs to coordinate access to array across multiple threads.

Collection Race with a Mutable Dictionary

In the following example, a mutable dictionary is enumerated in one thread while simultaneously being written to in another thread, without any access synchronization.

let dictionary: NSMutableDictionary = [:]
var sum: Int = 0
// Executed on Thread #1
for key in dictionary.keyEnumerator() {
    sum += dictionary[key] as! Int
}
// Executed on Thread #2
dictionary["forty-two"] = 42

Solution

Use Dispatch APIs to coordinate access to dictionary across multiple threads.

See Also

Thread Sanitizer Checks

Data Races

Detects unsynchronized access to mutable state across multiple threads.

Swift Access Races

Detects when multiple threads call a mutating method on the same structure, or pass a shared variable as inout without synchronization.

Uninitialized Mutexes

Detects when a mutex is used before it’s initialized.

Thread Leaks

Detects when threads aren’t closed after use.