-
-
Save hguandl/808135a6e0936bb28a5bf4709d9f04ea to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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