In this exercise we will take our interactive server and add a common log for lengths of messages that each client sends us. We will explore synchronization primitives that Rust offers in its Standard Library.
-
share data between threads using
Mutex
es -
use reference-counting to ensure data stays available across multiple threads
-
use scoped threads to avoid runtime reference counting
-
use channels and message passing to share data among threads by communicating
- Add a log to store length of messages:
let mut log: Vec<usize> = vec![];
- Pass it to a
handle_client
function and record a length of each incoming line of text:log.push(line.len());
- Resolve lifetime issues by using a reference-counting pointer.
- Resolve mutability issues by using a mutex
- Use the
thread::scope
function to get rid of reference counting forlog
vector
- Instead of sharing
log
vector use ampsc::channel
to send length of lines from worker threads. - Create a separate thread that listens for new channel messages and updates the vector accordingly.