// A producer task sends 0..4; the consumer receives until closed and closes the receiver, // which is carried through the loop and rebound on `pending`. // expect: run // grant: heap=mem.alloc:64 // schedules: 20 // quantum: 2 // result: 10 // equivalent: phase3/run/channels_producer_consumer.air // phase: 6 // spec: docs/spec/15-source-language.md module demo.producerconsumer fn produce(tx: sender, n: u64) -> u8 effects [task.wait] { var i: u64 = 0; while i != n { match channel.send(tx, i) { ok => {} closed(w) => { break; } cancelled(w) => { break; } } i = i + 1; } channel.close_sender(move tx); 0 } fn main(heap: cap) -> u64 effects [mem.alloc, task.spawn, task.wait] { match channel.make(2, heap) { ok(tx, rx) => { var acc: u64 = 0; scope sc { let t = task.spawn(sc, produce, move tx, 5); var r: receiver = move rx; loop { match channel.recv(r) { ok(v) => { acc = acc + v; } closed => { match channel.close_receiver(move r) { ok => { break; } pending(r) => {} } } cancelled => { match channel.close_receiver(move r) { ok => { break; } pending(r) => {} } } } } let x = task.join(move t); } acc } err(e) => { trap; } } }