Skip to content

Instantly share code, notes, and snippets.

@hguandl
Last active October 18, 2024 14:45
Show Gist options
  • Save hguandl/808135a6e0936bb28a5bf4709d9f04ea to your computer and use it in GitHub Desktop.
Save hguandl/808135a6e0936bb28a5bf4709d9f04ea to your computer and use it in GitHub Desktop.
func sequentialize<T: Sendable, each P: Sendable>(
fn: @Sendable @escaping (repeat each P) async -> (T)
) -> @Sendable (repeat each P) async -> (T) {
let (s, c) = AsyncStream.makeStream(of: Void.self)
c.yield(())
return { (x: repeat each P) in
var i = s.makeAsyncIterator()
await i.next()
let result = await fn(repeat each x)
c.yield(())
return result
}
}
let clock = ContinuousClock()
let sequentializedPlus = sequentialize { (a: Int, b: Int) in
try? await Task.sleep(for: .seconds(1))
print(clock.now, a, b)
return a + b
}
await withTaskGroup(of: Void.self) { group in
print(clock.now)
group.addTask {
print(await sequentializedPlus(1, 2))
}
group.addTask {
print(await sequentializedPlus(3, 4))
}
await group.waitForAll()
}
/*
Instant(_value: 1214028.911775166 seconds)
Instant(_value: 1214029.9298497501 seconds) 1 2
3
Instant(_value: 1214030.983612708 seconds) 3 4
7
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment