52 lines
1.6 KiB
Rust
52 lines
1.6 KiB
Rust
// Run: aji run --fuel 100000 --grant heap=mem.alloc:256 examples/channel_transfer.aji
|
|
module examples.channel_transfer
|
|
|
|
struct Message {
|
|
id: u64
|
|
}
|
|
|
|
fn producer(tx: sender<island<Message>>, heap: cap<mem.alloc>) -> void effects [mem.alloc, task.wait] {
|
|
let message = island.create(Message { id: 0u64 }, heap) or trap;
|
|
{
|
|
mut graph = message;
|
|
let address = island.root(graph);
|
|
mut root = island.at(graph, address);
|
|
root.id = 42u64;
|
|
}
|
|
match channel.send(tx, move message) {
|
|
ok => {}
|
|
closed(back) => {
|
|
island.destroy(move back);
|
|
} cancelled(back) => {
|
|
island.destroy(move back);
|
|
}
|
|
}
|
|
// The producer cannot use message after its ownership transfer.
|
|
channel.close_sender(move tx);
|
|
}
|
|
|
|
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc, task.spawn, task.wait] {
|
|
match channel.make<island<Message>>(1usize, heap) {
|
|
ok(tx, rx) => {
|
|
var result: u64 = 0;
|
|
scope s {
|
|
let t = task.spawn(s, producer, move tx, heap);
|
|
let message = channel.recv(rx) or trap;
|
|
{
|
|
ref graph = message;
|
|
let address = island.root(graph);
|
|
ref root = island.at(graph, address);
|
|
result = root.id;
|
|
}
|
|
island.destroy(move message);
|
|
task.join(move t);
|
|
}
|
|
channel.close_receiver(move rx) or trap;
|
|
result
|
|
}
|
|
err(error) => {
|
|
trap;
|
|
}
|
|
}
|
|
}
|