I am trying to make a rust app that can create, start & stop multiple simple REST servers.
For this, I use rouille.
I store the serverInstances using a hashMap behind a lazyLock:
struct ServerInstance {
...
stop: (JoinHandle<()>, Sender<()>),
}
static SERVER_INSTANCES: LazyLock<Mutex<HashMap<usize, ServerInstance>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
async fn start_server(id: usize, port: i16) {
let server = Server::new(format!("0.0.0.0:{}", port), |request| {
Response::text("hello world")
})
.unwrap();
SERVER_INSTANCES.lock().unwrap().insert(
id,
ServerInstance { ..., stop: server.stoppable() },
);
}
However, when I try to stop the server using this function:
fn stop_server_command(id: usize) {
if let Some(instance) = SERVER_INSTANCES.lock().unwrap().get(&id) {
let (handler, signal) = &instance.stop;
signal.send(()).unwrap();
handler.join().unwrap();
// ^^^^^^^ ------ `*handler` moved due to this method call
}
}
I get this error on handler.join():
error[E0507]: cannot move out of `*handler` which is behind a shared reference
--> srclib.rs:47:9
|
47 | handler.join().unwrap();
| ^^^^^^^ ------ `*handler` moved due to this method call
| |
| move occurs because `*handler` has type `std::thread::JoinHandle<()>`, which does not implement the `Copy` trait
|
note: `std::thread::JoinHandle::<T>::join` takes ownership of the receiver `self`, which moves `*handler`
Any ideas on how I should handle this?
1