FB6684220
my app that worked fine under Xcode 10 crashes under Xcode 11 (beta 3). I distilled the crash down to this: when accessing dictionary concurrently some of the acceses crash. interestingly it happens only under iOS, not under macOS. FB6684220
========
import Foundation
var dict: [String : String] = [:]
func test() {
Thread.detachNewThread {
var counter = 0
while true {
counter += 1
let key = String.random
dict[key] = .random
usleep((0...1000).randomElement()!)
}
}
Thread.detachNewThread {
var counter = 0
while true {
counter += 1
let key = String.random
let value = dict[key]
usleep((0...1000).randomElement()!)
}
}
}
extension String {
static var random: String {
let s = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. "
let offset = (0 ... 100).randomElement()!
let len = (1 ... 100).randomElement()!
return String(s[s.index(s.startIndex, offsetBy: offset) ... s.index(s.startIndex, offsetBy: offset + len)])
}
}
It is not safe to share unprotected mutable data (like
dict
) between threads. The fact that this didn’t crash in Xcode 10 is just an artefact of its implementation.
Fortunately there’s a way to flush out latent threading bugs like this one, namely, the thread sanitiser. If you run your code under the thread sanitiser, it immediately fails.
Share and Enjoy
—
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"