Here is a code snippet (from Aubrey Kate lesson about GCD) that will make the Xcode
Thread sanitizer
(A.K.A TSan
) - detect a Data race
:
import UIKit
final class MainViewController: UIViewController {
var counter = 0
override func viewDidLoad() {
super.viewDidLoad()
let queue = DispatchQueue(label: "q")
queue.async {
for _ in 1 ... 10000 {
Thread.sleep(forTimeInterval: 0.1)
self.counter += 1
}
}
DispatchQueue.main.async {
for _ in 1 ... 10000 {
self.counter += 1
}
}
}
}
But if I comment out the Thread.sleep(forTimeInterval: 0.1)
- The TSan
has no beef with me and will not crash the program.
My question is what essentially changed that the TSan
is unable to detect the Data race??? why is it that the TSan need the Thread.sleep
function to be able to locate the data race
and without it, it's unable.