0

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.

Hudi Ilfeld
  • 1,905
  • 2
  • 16
  • 25
  • 1
    Today processors is fast enough to finish your first cycle before next async start with second, so no race over `counter`, but when you add `sleep` you make them overlapped, and sanitizer detects this. What you do is incorrect - `counter` should be either synchronised, - worse case, or updated on one queue, - correct case. – Asperi Aug 30 '20 at 15:18
  • 1
    See the section on "Extended happens-before arc" in http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/35604.pdf. In particular: "In the pure happens-before mode, ThreadSanitizer will behave differently: if the race is real, the race may or may not be reported (depends on timing, this is why the pure happens-before mode is less predictable); if there is no race, the tool will be silent." – Rob Napier Aug 30 '20 at 16:35
  • @Asperi I am studying the nature of data races. solving them is not the purpose. Vice versa – Hudi Ilfeld Aug 30 '20 at 19:54

0 Answers0