gpt4 book ai didi

ios - 确保两个计时器的执行逻辑不会同时运行

转载 作者:行者123 更新时间:2023-12-01 18:03:31 24 4
gpt4 key购买 nike

我有两个计时器,它们以不同的时间间隔运行,其中一个添加到运行循环中。

let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
// do some stuff
}

let timer2 = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { timer in
// do some other stuff
}
RunLoop.current.add(timer2, forMode: RunLoop.Mode.common)

我有一个条件,要求两个计时器的执行逻辑不能同时运行,因为它们都在修改相同的数据结构。

iOS已经保证了吗?如果没有,确保这种情况发生的最佳方法是什么?

最佳答案

只要您将计时器安排在相同的RunLoop上,就很安全。 RunLoop始终与一个线程关联,因此将在该线程上执行块。因此,它们永远不会在同一时间开火。
但是,如果将它们安排在两个不同的RunLoop实例上,情况将会有所不同。
当您说仅将一个计时器添加到RunLoop时,我不确定您的意思。如果您不将计时器添加到RunLoop,则它将完全不触发。

关于ios - 确保两个计时器的执行逻辑不会同时运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62442532/

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