import Foundation class AsyncPipe { let pipe: Pipe let task: Task<(), Error> typealias continuation = UnsafeContinuation init() { self.pipe = Pipe() self.task = Task.detached { [pipe = self.pipe] in while (!Task.isCancelled) { let data = try pipe.fileHandleForReading.read(upToCount: 8)! let raw = data.reduce(0) { $0 << 8 + UInt64($1) } let cont = unsafeBitCast(raw, to: continuation.self) cont.resume(returning: Int.random(in: 0...4)) } } } func nop() async -> Int { return await withUnsafeContinuation() { cont in let raw = unsafeBitCast(cont, to: UInt64.self) withUnsafeBytes(of: raw.bigEndian) { buf in try! self.pipe.fileHandleForWriting.write(contentsOf: buf) } } } deinit { self.task.cancel() } } func pipeBenchmark() async { let ring = AsyncPipe() var sum = 0 for _ in 1...100000 { sum += await ring.nop() } print("Done! Random output:", sum) } await pipeBenchmark()