我遇到了一个线程冲突问题,即串行队列中的任务与定时器同时运行,在同一个串行队列中,概率非常低,但会长期发生。
下面的是swift 3.0中的示例代码。
import Foundation
func printTrace(_ str: String) {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
let strDate = formatter.string(from: Date())
let tid = pthread_mach_thread_np(pthread_self())
print("\(strDate) [\(tid)] \(str)")
}
let queue1 = DispatchQueue(label: "timer-test-queue1")
let queue2 = DispatchQueue(label: "timer-test-queue2")
func asyncBlock() {
printTrace("asyncBlock")
}
func timerBlock() {
printTrace("timerBlock 1")
queue2.async {
queue1.async {
asyncBlock()
}
}
printTrace("timerBlock 2")
}
let timer = DispatchSource.makeTimerSource(flags: DispatchSource.TimerFlags.strict, queue: queue1)
timer.scheduleRepeating(deadline: DispatchTime.now(), interval: Double(0.05/* 50 ms */), leeway: .milliseconds(1))
timer.setEventHandler {
timerBlock()
}
timer.resume()
有时会显示:
timerBlock 1
asyncBlock
timerBlock 2