Hyper has the following example of a Handler
that implements Sync
:
use std::sync::Mutex;
use std::sync::mpsc::{channel, Sender};
use hyper::server::{Handler, Server, Request, Response};
struct SenderHandler {
sender: Mutex<Sender<&'static str>>
}
impl Handler for SenderHandler {
fn handle(&self, req: Request, res: Response) {
self.sender.lock().unwrap().send("start").unwrap();
}
}
and states that a Handler
must implement Sync
, since Handler
can be called from different threads.
To me, this sounds like an unnecessary performance penalty. What I would prefer would be to setup one SenderHandler
per thread, each being independent, which would remove the requirement on implementing Sync
.
Have I misunderstood Hyper, Rust's type-system or is this not possible?
Ok, so this actually seems impossible at the moment in Hyper. It is discussed in issue 248 and the developer prefers Sync
over Clone
:
We talked through this on IRC. Simple synopsis is that if it were
Clone
, users could easily have state on their handler that they think is modified with each request, but instead, it would have been cloned several times and not modify what they hoped. Instead, it's better force the user to make sure their state is synchronized.