1

看起来 Swift 新的并发模型与旧的并发模型不兼容。我已经尝试为我的新异步函数逐步采用新的 swift 并发模型(使用 async/await 仪式),但是当避免数据竞争问题的传统方法(在串行队列上调度任务)确实如此时,我很快就碰壁了不再工作了。我知道新模型使用演员来处理这个问题,但我认为 2 世界可以生活​​在一起,但没有找到解决方案。为了证明我的问题,请检查以下代码。Playground 结果表明,Task 2 的一些代码在 Task 1 完成之前执行,这使得 queue.async 无能为力,这与开发人员的预期背道而驰。有没有办法在不使用演员的情况下序列化任务?

import Foundation
import _Concurrency

DispatchQueue.main.async{
  print("1")
  Task{
    print("1.1")
    try await Task.sleep(nanoseconds: 1000000000)
    print("1.1.1")
  }
  print("1.1.1.1")
}

DispatchQueue.main.async{
  print("2")
  Task{
    print("2.2")
    try await Task.sleep(nanoseconds: 1000000000)
    print("2.2.2")
  }
  print("2.2.2.2")
}


result:
1
1.1.1.1
2
2.2.2.2
1.1
2.2
2.2.2
1.1.1
4

0 回答 0