-
struct LocalSpawner {
send: mpsc::UnboundedSender<Handler>,
}
impl LocalSpawner {
pub fn new() -> Self {
let (send, mut recv) = mpsc::unbounded_channel::<Handler>();
std::thread::spawn(move || {
let local = LocalSet::new();
let rt = Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
local.spawn_local(async move {
while let Some(mut handler) = recv.recv().await {
// Process the connection. If an error is encountered, log it.
// handle.run will be loop runing inside until connection close
if let Err(err) = handler.run().await {
println!("Connection Error: {:?}", &err);
error!(cause = ?err, "connection error");
}
}
// If the while loop returns, then all the LocalSpawner
// objects have have been dropped.
});
rt.block_on(local);
});
Self {
send,
}
}
pub fn spawn(&self, handler: Handler) {
self.send.send(handler).expect("Thread with LocalSet has shut down.");
}
} As the code example in tokio docs, the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
You should use |
Beta Was this translation helpful? Give feedback.
You should use
tokio::task::spawn_local
inside your loop whenever you receive a new connection.