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.

NSMutableArray *array = [NSMutableArray new];
NSInteger sum = 0;
// Executed on Thread #1
for (id value in array) {  
    sum += [value integerValue];
} 
// Executed on Thread #2
[array addObject:@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.

NSMutableDictionary *dictionary = [NSMutableDictionary new];
NSInteger sum = 0;
// Executed on Thread #1
for (id key in dictionary) {
    sum += [dictionary[key] integerValue];
}
// 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.