AsyncSerialQueue
是一个使用 Swift 并发提供的实用模式库。
AsyncSerialQueue
是一个类,它使用 Swift 并发 提供类似 串行队列 的功能。 放入 AsyncSerialQueue
的任务保证按顺序执行。
AsyncCoalescingQueue
是一个伴随类,具有与 DispatchSource 相似的属性。
AsyncSerialQueue 目前仅在 Apple 平台(即不在 Linux 上)可用。 这是因为需要锁定,并且 Swift 目前没有标准的跨平台锁定机制。
let serialQueue = AsyncSerialQueue()
func example() {
serialQueue.async {
print("1")
}
serialQueue.async {
print("2")
}
serialQueue.async {
print("3")
}
print("apple")
}
请注意,此处不需要将 example()
声明为 async
。
数字将始终按顺序输出
1
2
3
但是,不能保证 apple
可能出现在哪里
apple
1
2
3
或者
1
2
apple
3
或任何其他组合
在某些情况下(例如,单元测试),您可能需要等待串行队列为空。
func example() async {
serialQueue.async {
print("1")
}
await serialQueue.wait()
serialQueue.async {
print("2")
}
}
在打印 1
之后,example()
将不会完成返回。 但是,它可能会在输出 2
之前返回。
类似地,如果寻找类似于 屏障块 的东西
func example() async {
serialQueue.async {
print("1")
}
await serialQueue.sync {
print("2")
}
serialQueue.async {
print("3")
}
print("apple"")
}
在这种情况下,apple
永远不会出现在 2
之前。 并且 example()
在打印 2
之前不会返回。
以下代码
let coalescingQueue = AsyncCoalescingQueue()
coalescingQueue.run {
try? await Task.sleep(for: .seconds(5))
print("Run 1")
}
coalescingQueue.run {
try? await Task.sleep(for: .seconds(5))
print("Run 2")
}
coalescingQueue.run {
try? await Task.sleep(for: .seconds(5))
print("Run 3")
}
coalescingQueue.run {
try? await Task.sleep(for: .seconds(5))
print("Run 4")
}
coalescingQueue.run {
try? await Task.sleep(for: .seconds(5))
print("Run 5")
}
将输出以下内容
Run 1
Run 5
并且需要 10 秒才能完成执行。