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

使用RxSwift更新CollectionView时,跨线程更新UI为何引发死锁?

RxSwift后台线程更新UI引发死锁的原因疑问

问题概述

我明确UI更新必须在主线程执行,当前死锁问题出自两段RxSwift更新CollectionView的代码:

  • 第一段通过Driver在主线程更新matchCollectionView和matchCountLabel
  • 第二段通过subscribe在后台线程执行完全相同的UI更新操作

我已经移除后台线程的UI更新代码解决了问题,但对死锁的具体成因存在疑惑。结合死锁时的调用栈截图,我初步猜测是主线程与后台线程互相等待:后台线程触发主线程执行UI更新后进入等待状态,而主线程也在等待后台线程完成视图更新,但不确定后台线程为何会因调用主线程被锁定,想了解Xcode判定死锁的具体依据。

相关代码

let allMatchObservable = output.allMatchObservable.share()

allMatchObservable
    .asDriver(onErrorJustReturn: [])
    .drive { [weak self] matchs in
        guard let owner = self else { return }
        owner.matchCollectionView.setData(section: .none, matchInfos: matchs.map { MatchInfo(match: $0, owner: User()) })
        owner.matchCountLabel.text = "\(matchs.count)개"
    }
    .disposed(by: disposeBag)

let selectSportObservable = output.selectSportObservable.share()

selectSportObservable
    .withUnretained(self)
    .subscribe { owner, matchs in
        owner.matchCollectionView.setData(section: .none, matchInfos: matchs.map { MatchInfo(match: $0, owner: User()) })
        owner.matchCountLabel.text = "\(matchs.count)개"
    }
    .disposed(by: disposeBag)

死锁相关调用栈截图

  • 死锁状态捕获截图
  • 主线程调用栈捕获截图
  • 后台线程调用栈捕获截图

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 04:52:38