Synchronous concurrency: Difference between revisions
Content added Content deleted
Thundergnat (talk | contribs) m (Fix Perl 6 -> Raku in comments) |
|||
Line 2,438: | Line 2,438: | ||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
{{works with|rustc 1. |
{{works with|rustc 1.46.0 (04488afe3 2020-08-24)|}} |
||
<lang rust>use std::fs::File; |
<lang rust>use std::fs::File; |
||
⚫ | |||
use std::io::BufRead; |
use std::io::BufRead; |
||
⚫ | |||
use std:: |
use std::sync::mpsc::{channel, sync_channel}; |
||
use std::thread; |
|||
use std::sync::mpsc::{SyncSender, Receiver, sync_channel}; |
|||
fn main() { |
fn main() { |
||
// The reader sends lines to the writer via an async channel, so the reader is never blocked. |
|||
let (tx, rx): (SyncSender<String>, Receiver<String>) = sync_channel::<String>(0); |
|||
let (reader_send, writer_recv) = channel(); |
|||
// The writer sends the final count via a blocking channel with bound 0, |
|||
⚫ | |||
// meaning the buffer is exactly the size of the result. |
|||
⚫ | |||
let (writer_send, reader_recv) = sync_channel(0); |
|||
⚫ | |||
// Define the work the reader will do. |
|||
⚫ | |||
⚫ | |||
let reader = BufReader::new(file); |
let reader = BufReader::new(file); |
||
for line in reader.lines() { |
for line in reader.lines() { |
||
match line { |
match line { |
||
Ok(msg) => |
Ok(msg) => reader_send |
||
.send(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(reader_send); |
|||
// Now that we've sent all the lines, |
|||
// Writer thread. |
|||
// block until the writer gives us the final count. |
|||
⚫ | |||
let |
let count = reader_recv |
||
⚫ | |||
.expect("Failed to receive count from printer."); |
|||
println!("{}", count); |
|||
}; |
|||
⚫ | |||
// Define the work the writer will do. |
|||
⚫ | |||
let mut line_count = 0; |
|||
loop { |
|||
match writer_recv.recv() { |
|||
Ok(msg) => { |
Ok(msg) => { |
||
println!("{}", msg); |
println!("{}", msg); |
||
line_count += 1; |
|||
} |
} |
||
Err(_) => break // |
Err(_) => break, // indicates the connection has been closed by the sender. |
||
} |
} |
||
} |
} |
||
// Send the final count back to the reader. |
|||
writer_send |
|||
⚫ | |||
.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> |
}</lang> |
||