You need to enable JavaScript to run this app. 如何以线程安全方式执行Combine链并保护可变状态?
优惠活动
大模型
产品
解决方案
定价
更多

如何以线程安全方式执行Combine链并保护可变状态?

用Combine重写Operation串行队列业务流的状态同步问题

我现有一套通过Operation子类与OperationQueue实现的业务流程,希望通过Combine重写该流程作为学习练习。

当前简化版的原有实现代码如下:

func testFunction(completionHandler: (Result) -> Void) {
    let op = LongRunningOperation(object: self.stateObject)

    op.completionHandler = { [unowned op] in
        let result = op.result
        self.stateObject.update(with: result)

        completionHandler(result)
    }

    localSerialQueue.addOperation(op)
}

该实现的关键约束包括:

  • LongRunningOperation为异步操作,根据stateObject的状态可能需要调用主队列完成登录流程
  • stateObject仅在localSerialQueue队列中被访问
  • runOperation可能存在并发调用场景,队列与操作提供的串行化能力是保障正确性的核心

可变状态与潜在并发调用的组合是本问题的核心关键。

为说明该问题,我编写了示例代码验证Combine管道并非原子执行:其他结果本会令我意外,我仅为验证该特性——多个线程可同时执行管道的不同阶段,会触发前置条件校验失败,示例代码如下:

class MyThreadUnsafeObject {
    private var cancellables = Set<AnyCancellable>()
    private var inProcess = false

    private func testFunction() {
        Result<Bool, Error> {
            // begin our pipeline, checking our invariant
            // and mutating the state to start our process
            precondition(self.inProcess == false)

            self.inProcess = true

            // just pass some dummy data through
            return true
        }
        .publisher
        .flatMap { (result: Bool) -> AnyPublisher<Bool, Error> in
            Future { (promise) in
                precondition(self.inProcess)

                // simulate a very simple long-running task here,
                // which is not even asynchronous, just to make things
                // really clear.

                // critically, change some mutable state only
                // when done

                precondition(self.inProcess)
                sleep(2)
                precondition(self.inProcess)

                promise(.success(true))
            }.eraseToAnyPublisher()
        }
        .sink(receiveCompletion: { completion in
            if case .failure = completion {
                fatalError("this isn't allowed to happen")
            }
        }, receiveValue: { result in
            precondition(result == true)
            precondition(self.inProcess)

            // back to the initial state
            self.inProcess = false
        })
        .store(in: &self.cancellables)
    }

    func runTest() {
        let group = DispatchGroup()

        for _ in 0..<20 {
            DispatchQueue.global().async(group: group, qos: .default, flags: .inheritQoS) {
                self.testFunction()
            }
        }

        group.wait()
    }
}

需要特别说明的是,我的问题并非如何搭建Combine管道,而是关注Combine同步原语的语义:

  • 如何保护管道访问范围内的可变状态
  • 是否可配合锁等其他同步手段适配该访问模式
  • 是否有其他开发者遇到过同类问题
  • 是否有更符合Combine设计习惯的实现方案
  • 是否有可调整的问题重构思路

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.20 16:24:03