swift 独立线程中的定时器
swift timer in a separate thread
我有下一个代码:
private var timer: dispatch_source_t?
private let queue = dispatch_queue_create("queue", DISPATCH_QUEUE_SERIAL)
private func startTimer() {
timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue)
dispatch_source_set_timer(timer!, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 1 * NSEC_PER_SEC)
dispatch_source_set_event_handler(timer!) {
self.process()
}
dispatch_resume(timer!)
}
private func stopTimer() {
if timer != nil {
dispatch_source_cancel(timer!)
timer = nil
}
}
public func callNow() {
dispatch_async(queue, {self.process()})
}
private func process() {
Log.d(tag, message: "process currentThread=\(NSThread.currentThread())")
}
为什么我在两个不同的线程中有 process
方法调用?
process currentThread=<NSThread: 0x7f8080e01880>{number = 2, name = (null)}
process currentThread=<NSThread: 0x7f8080e03d40>{number = 3, name = (null)}
process currentThread=<NSThread: 0x7f8080e03d40>{number = 3, name = (null)}
process currentThread=<NSThread: 0x7f8080e03d40>{number = 3, name = (null)}
不要混淆线程和操作队列。一个操作队列中的任务在不同的线程上执行是完全正常的。来自 Apple's documentation:
Serial queues (also known as private dispatch queues) execute one task at a time in the order in which they are added to the queue. The currently executing task runs on a distinct thread (which can vary from task to task) that is managed by the dispatch queue. Serial queues are often used to synchronize access to a specific resource.
我有下一个代码:
private var timer: dispatch_source_t?
private let queue = dispatch_queue_create("queue", DISPATCH_QUEUE_SERIAL)
private func startTimer() {
timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue)
dispatch_source_set_timer(timer!, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 1 * NSEC_PER_SEC)
dispatch_source_set_event_handler(timer!) {
self.process()
}
dispatch_resume(timer!)
}
private func stopTimer() {
if timer != nil {
dispatch_source_cancel(timer!)
timer = nil
}
}
public func callNow() {
dispatch_async(queue, {self.process()})
}
private func process() {
Log.d(tag, message: "process currentThread=\(NSThread.currentThread())")
}
为什么我在两个不同的线程中有 process
方法调用?
process currentThread=<NSThread: 0x7f8080e01880>{number = 2, name = (null)}
process currentThread=<NSThread: 0x7f8080e03d40>{number = 3, name = (null)}
process currentThread=<NSThread: 0x7f8080e03d40>{number = 3, name = (null)}
process currentThread=<NSThread: 0x7f8080e03d40>{number = 3, name = (null)}
不要混淆线程和操作队列。一个操作队列中的任务在不同的线程上执行是完全正常的。来自 Apple's documentation:
Serial queues (also known as private dispatch queues) execute one task at a time in the order in which they are added to the queue. The currently executing task runs on a distinct thread (which can vary from task to task) that is managed by the dispatch queue. Serial queues are often used to synchronize access to a specific resource.