Skip to content

Instantly share code, notes, and snippets.

@niw
Last active June 13, 2021 07:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niw/80d04de9bc9354ff224e3ee4ca1626eb to your computer and use it in GitHub Desktop.
Save niw/80d04de9bc9354ff224e3ee4ca1626eb to your computer and use it in GitHub Desktop.
import Foundation
func th() {
print(Thread.current)
}
th()
func a(_ i: Int) async -> Int {
th()
print("sleep \(i)")
sleep(1)
print("awake \(i)")
return i
}
let t = async {
th()
print("Task begin")
let i: Int = await withTaskGroup(of: Int.self) { g in
th()
print(g)
for i in 0..<20 {
// Add child task to the group
g.async {
await a(i)
}
}
var i = 0
// group conforms `AsyncSequence`
for await r in g {
i += r
print(r)
}
return i
}
print(i)
print("Task end")
}
print(t)
sleep(5)
print("Done")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment