You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift多线程调用含Timer的同一函数,如何分别获取各线程Timer值

问题原因

你的代码里所有Timer共享同一个全局变量ticker,每个Timer触发时都会对这个变量做自增操作,所以输出是连续递增的数字,而非每个Timer独立计数。

解决方案

要让每个Timer拥有独立的计数器,需要把计数器和对应的Timer订阅绑定。可以通过在multiplecall方法内部创建局部变量,让闭包捕获独立的计数器来实现。以下是修改后的Playground代码:

import Combine
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

private var update: [AnyCancellable] = []

func multiplecall(name: String) {
    // 每个Timer对应独立的计数器
    var ticker = 0
    Timer.publish(every: 1, on: .main, in: .common)
        .autoconnect()
        .sink { _ in
            ticker += 1
            print("\(name): \(ticker)")
        }
        .store(in: &update)
}

multiplecall(name: "test1")
multiplecall(name: "test2")
代码说明
  • 将ticker移至multiplecall方法内部,每次调用该方法创建Timer时,都会生成一个独立的计数器,不会和其他Timer的计数器互相干扰。
  • 在sink闭包中捕获这个局部ticker,每次Timer触发时仅对当前Timer对应的计数器自增,并打印Timer名称和对应计数,最终会输出test1: 1、test2: 1、test1: 2、test2: 2这类符合预期的结果。
  • Playground中需添加PlaygroundPage.current.needsIndefiniteExecution = true,否则Playground会直接结束,无法看到Timer的持续输出。

内容的提问来源于stack exchange,提问作者OhStack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 22:47:39