Many iOS developers began to learn structured concurrency has been used for many years Grand Central Dispatch, although from the idea that the two are very different, but the use of familiar things to understand the new things to help improve the efficiency of learning and understanding, the next is this Grand Central Dispatch common use of code and conversion code.
synchronous
// Original code
().async {
print("1")
print("1") {
print("3")
}
print("2")
}
// Conversion
{
print("1")
async let _ = await {
// Also use Task { @MainActor in
print("3")
}
print("2")
}
Asynchronous Serial Implemented with Signals
// Source code
().async {
let s = DispatchSemaphore(value: 0)
().async {
sleep(2) // simulate a time-consuming operation
print("1")
()
}
()
().async {
sleep(1) // simulate a time-consuming operation
print("2")
()
}
()
print("3")
}
// Convert
{
await Task {
sleep(2) // simulate a time-consuming operation
print("1")
}.value // .value is essential.
await Task {
sleep(1) // simulates a time-consuming operation
print("2")
}.value
print("3")
}
Asynchronous parallelism in combination with semaphores
// source code (computing)
().async {
let s = DispatchSemaphore(value: 0)
().async {
print("part1:1 or 2")
()
}
().async {
print("part2:1 or 2")
()
}
()
()
print("3")
}
// conversions
{
async let a1: () = await Task {
print("part1:1 or 2")
}.value
async let a2: () = await Task {
print("part2:1 or 2")
}.value
let (_, _) = await(a1, a2)
print("3")
}