I'm creating a network distributor. I have a member variable that is a potentially very large vector. I need a separate thread to handle when I need to write the vector to disk as I can not risk it blocking the network.
I want to send the vector to the writer_thread
(probably moving it is required so it doesn't take time) and then let the main thread start working with a new vector while the writer_thread
does its job without interrupting the main program.
use std::sync::mpsc::{self, channel};
use std::thread;
struct NetDist {
sender: mpsc::Sender<Vec<Object>>,
large_vec: Vec<Object>,
}
impl NetDist {
fn new() -> Netdist {
let (sender, receiver) = channel::<Vec<Message>>();
NetDist {
sender,
large_vec: Vec::new(),
};
thread::spawn(move || NetDist::writer_thread(receiver));
}
fn main_thread(&mut self) {
loop {
// Do stuff and fill up large_vec
// Here I want to move the memory of large_vec to the writer_thread
// and allocate new memory for large_vec that will be sent later.
// ERROR: Cannot move out of borrowed content
self.sender.send(self.large_vec);
// Allocate new memory and let writer_thread handle the sent memory
self.large_vec = Vec::new();
}
}
fn writer_thread(receiver: mpsc::Receiver<Vec<Object>>) {
loop {
let mut largevec = receiver.recv().unwrap();
// Write to disk....
// Free memory when writing is done
largevec.clear();
}
}
}