Created
August 22, 2018 10:14
-
-
Save zesterer/968f0ff6c4658a45c923070313334375 to your computer and use it in GitHub Desktop.
A pattern for correctly managing worker threads associated with an instance in Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Server; | |
impl Server { | |
fn new() -> Server { | |
Server | |
} | |
} | |
struct ServerMgr { | |
server: Arc<Server>, | |
running: Arc<AtomicBool>, | |
worker: Option<JoinHandle<()>>, | |
} | |
impl ServerMgr { | |
fn init(server: Server) -> ServerMgr { | |
let server = Arc::new(server); | |
let running = Arc::new(AtomicBool::new(true)); | |
// Start worker thread | |
let server_ref = server.clone(); | |
let running_ref = running.clone(); | |
let worker = Some(thread::spawn(move || Self::worker(server_ref, running_ref))); | |
ServerMgr { server, running, worker } | |
} | |
fn worker(server: Arc<Server>, running: Arc<AtomicBool>) { | |
while running.load(Ordering::Relaxed) { | |
// Do something with the server here | |
} | |
} | |
fn server(&self) -> &Arc<Server> { &self.server } | |
} | |
impl Drop for ServerMgr { | |
fn drop(&mut self) { | |
self.running.store(false, Ordering::Relaxed); | |
self.worker.take().map(|w| w.join()); | |
} | |
} | |
fn main() { | |
let server_mgr = ServerMgr::init(Server::new()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment