Anonymous user
Synchronous concurrency: Difference between revisions
→{{header|Rust}}
Thundergnat (talk | contribs) m (Fix Perl 6 -> Raku in comments) |
|||
Line 2,438:
=={{header|Rust}}==
{{works with|rustc 1.
<lang rust>use std::fs::File;
use std::io::BufReader;▼
use std::io::BufRead;
▲use std::io::BufReader;
use std::
use std::thread;
fn main() {
// The reader sends lines to the writer via an async channel, so the reader is never blocked.
let (reader_send, writer_recv) = channel();
// The writer sends the final count via a blocking channel with bound 0,
// Reader thread.▼
// meaning the buffer is exactly the size of the result.
spawn(move || {▼
let (writer_send, reader_recv) = sync_channel(0);
let file = File::open("input.txt").unwrap();▼
// Define the work the reader will do.
let reader = BufReader::new(file);
for line in reader.lines() {
match line {
Ok(msg) =>
.expect("Failed to send via the channel"),
Err(e) => println!("{}", e),
}
}
// Dropping the sender disconnects it and tells the receiver the connection is closed.
drop(tx);▼
// Now that we've sent all the lines,
// block until the writer gives us the final count.
spawn(move || {▼
let
.expect("Failed to receive count from printer.");
};
▲ let recvd = rx.recv();
// Define the work the writer will
let mut line_count = 0;
loop {
match writer_recv.recv() {
Ok(msg) => {
println!("{}", msg);
}
Err(_) => break, //
}
}
writer_send
}).join().unwrap();▼
.send(line_count)
.expect("Failed to send line count from writer.");
};
let reader_handle = thread::spawn(reader_work);
thread::spawn(writer_work);
reader_handle
.expect("Failed to join the reader thread.");
}</lang>
|