refactor: use parking_lot instead of std::sync

This commit is contained in:
Nova
2022-06-12 01:51:12 -04:00
parent 01971b5048
commit d308b88bb7
3 changed files with 12 additions and 29 deletions

View File

@@ -7,31 +7,23 @@ use mio::{Events, Interest, Poll, Token};
use slab::Slab;
use std::io::Write;
use std::rc::Rc;
use std::sync::{Arc, RwLock};
use std::thread::{self, JoinHandle};
pub struct EventLoop {
pub socket_path: String,
join_handle: RwLock<Option<JoinHandle<Result<()>>>>,
join_handle: Option<JoinHandle<Result<()>>>,
stop_write: pipe::Sender,
}
impl EventLoop {
pub fn new(timeout: Option<core::time::Duration>) -> Result<Arc<Self>> {
pub fn new(timeout: Option<core::time::Duration>) -> Result<Self> {
let socket_path = server::get_free_socket_path()
.ok_or_else(|| std::io::Error::from(std::io::ErrorKind::Other))?;
let mut socket = UnixListener::bind(socket_path.clone())?;
let (sender, mut receiver) = pipe::new()?;
let event_loop_arc = Arc::new(EventLoop {
socket_path,
join_handle: RwLock::new(None),
stop_write: sender,
});
let event_loop_arc_captured = event_loop_arc.clone();
let join_handle = thread::Builder::new()
.name("event_loop".to_owned())
.spawn(move || -> Result<()> {
let event_loop_arc = event_loop_arc_captured;
let mut clients: Slab<Option<Rc<Client>>> = Slab::new();
let mut poll = Poll::new()?;
let mut events = Events::with_capacity(1024);
@@ -54,8 +46,7 @@ impl EventLoop {
Token(client_number),
Interest::READABLE,
)?;
let client =
Client::from_connection(socket, &event_loop_arc);
let client = Client::from_connection(socket);
*clients.get_mut(client_number).unwrap() = Some(client);
}
Err(e) => {
@@ -83,12 +74,11 @@ impl EventLoop {
}
})
.ok();
event_loop_arc.set_join_handle(join_handle);
Ok(event_loop_arc)
}
fn set_join_handle(&self, handle: Option<JoinHandle<Result<()>>>) {
*self.join_handle.write().unwrap() = handle;
Ok(EventLoop {
socket_path,
join_handle,
stop_write: sender,
})
}
}
@@ -98,10 +88,9 @@ impl Drop for EventLoop {
let _ = self.stop_write.write(buf.as_slice());
let _ = self
.join_handle
.get_mut()
.ok()
.and_then(|handle| handle.take())
.take()
.and_then(|handle| handle.join().ok())
.as_ref()
.expect("Couldn't join the event loop thread at drop");
}
}