gpt4 book ai didi

ios - 单独线程中的快速计时器

转载 作者:行者123 更新时间:2023-11-28 12:51:03 25 4
gpt4 key购买 nike

我有下一个代码:

         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.

关于ios - 单独线程中的快速计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36518158/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com