Thread Sanitizer(TSan, 线程消毒剂🤔?), 是LLVM里Apple提供检测多线程开发中可能存在的资源竞争情况的工具。
不过它只能在模拟器上运行。
除了TSan之外,还有一些其他的Sanitizer,比如Address Sanitizer, Main Thread Chekcer。
例子
新建一个工程,在ViewController中加入代码
var counter = 0
override func viewDidLoad() {
super.viewDidLoad()
let queue = DispatchQueue(label: "example")
queue.async {
for _ in 1 ... 10000 {
Thread.sleep(forTimeInterval: 0.1)
self.counter += 1
}
}
DispatchQueue.main.async {
for _ in 1 ... 10000 {
self.counter += 1
}
}
}
两个线程同时对counter变量访问,会产生竞争。下面我们运行Thread Sanitizer来检测一下
使用
在Edit Scheme中,勾选Thread Sanitizer












网友评论