<!--
{
  "documentType" : "article",
  "framework" : "Xcode",
  "identifier" : "/documentation/Xcode/races-on-collections-and-other-apis",
  "metadataVersion" : "0.1.0",
  "role" : "article",
  "title" : "Races on collections and other APIs"
}
-->

# Races on collections and other APIs

Detects when one thread accesses a mutable object while another thread is writing to it.

## Overview

In Xcode 9 and later, the Thread Sanitizer detects unsafe thread accesses of <doc://com.apple.documentation/documentation/Foundation> and <doc://com.apple.documentation/documentation/CoreFoundation> framework APIs. This feature applies to the following collection types:

- <doc://com.apple.documentation/documentation/Foundation/NSMutableArray>
- <doc://com.apple.documentation/documentation/Foundation/NSMutableDictionary>
- <doc://com.apple.documentation/documentation/CoreFoundation/CFMutableArray>
- <doc://com.apple.documentation/documentation/CoreFoundation/CFMutableDictionary>

### Collection race with a mutable array

In the following example, the code enumerates a mutable array in one thread while writing to the array from another without synchronizing access:

**Swift**

```swift
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)
```

**Objective-C**

```objc
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 <doc://com.apple.documentation/documentation/Dispatch> APIs to coordinate access to `array` across multiple threads.

### Collection race with a mutable dictionary

In the following example, the code enumerates a mutable dictionary in one thread while writing to the dictionary from another without synchronizing access:

```swift
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
```

**Objective-C**

```objc
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 <doc://com.apple.documentation/documentation/Dispatch> APIs to coordinate access to `dictionary` across multiple threads.

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)