Changes

Jump to: navigation, search

Team Hortons

2,417 bytes added, 21:07, 29 November 2017
Channels
== Channels ==
Instead of sharing memory, Rust encourages communication between thread in order to combine information. Channels, which are available in Rust's standard library, can be pictured as rivers: an object put into this river will be carried downstream. Likewise, a Channel has two parts: a sender and a receiver. The sender is responsible for putting information in the channel, which can be retrieved by the receiver. When we ask for a receiver to get a message from the channel, the execution may wait until the message is received or not: the method '''recv''' will block the execution, while '''try_recv''' will not.
The following example will spawn a thread, which will send a few strings down a channel which will be received by the main thread.
<source lang="rust">
use std::thread;
use std::sync::mpsc;
use std::sync::mpsc::{Sender, Receiver};
 
fn main() {
let (sender, receiver): (Sender<String>, Receiver<String>) =
mpsc::channel();
 
thread::spawn(move || {
let messages = vec![
String::from("blue"),
String::from("yellow"),
String::from("green"),
String::from("red"),
];
 
for colour in messages {
sender.send(colour).unwrap();
}
});
 
for message in receiver {
println!("Got {}", message);
}
 
}
</source>
 
This produces the following output:
 
<source>
Got blue
Got yellow
Got green
Got red
</source>
 
Similarly to the previous examples, the '''sender''' will be moved to the closure executed by the thread, which means that it will go out of scope when the thread finishes. To distribute the sender through several threads, they can be cloned: objects sent through this sender will still be received by the same receiver, but the two senders are different objects, which can have their ownership moved:
 
<source lang="rust">
use std::thread;
use std::sync::mpsc;
use std::sync::mpsc::{Sender, Receiver};
 
static NUM_THREADS: i32 = 8;
 
fn main() {
let mut vec = Vec::new();
 
let (send, receive): (Sender<i32>, Receiver<i32>) =
mpsc::channel();
 
for i in 0..NUM_THREADS {
// cloning the sender so it can be exclusive to the new thread
let thread_sender = send.clone();
 
thread::spawn(move || {
thread_sender.send(i).unwrap();
});
}
 
for _ in 0..NUM_THREADS {
vec.push(receive.recv().unwrap());
}
 
for i in vec.iter() {
println!("{}", i);
}
 
}
</source>
 
Output:
 
<source>
1
3
0
2
5
6
7
4
</source>
== Locks (Mutex) ==

Navigation menu