我正在创建网络分销商。我有一个成员变量,它可能是一个很大的向量。当我需要将向量写入磁盘时,我需要一个单独的线程来处理,因为我不能冒险将其阻塞网络。
我想将向量发送到writer_thread
(可能需要将其移动,因此不会花费时间),然后让主线程开始使用新的向量,而writer_thread
则它的工作不会中断主程序。
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();
}
}
}