#thread #managed #drop #automatically

managed-thread

Real fearless concurrency! Spawn threads that will be automatically destroyed when no longer needed

3 releases

0.0.3 Nov 16, 2020
0.0.2 Aug 6, 2020
0.0.1 Jan 24, 2020

#224 in Concurrency

29 downloads per month

MIT license

9KB
94 lines

managed-thread

crates.io

A rust library, allowing you to spawn threads that will be automatically destroyed when no longer needed

Installation

Add this to your Cargo.toml:

[dependencies]
managed-thread="0.0.1"

lib.rs:

The goal of this library is to allow you to create worker threads, whilst being confident that they will be cleaned up again and you don't "leak" threads.

This is achieved by passing a Signal object to the newly spawned thread. The thread is responsible for checking this signal for whether it should terminate or not.

Therefore this library's concept is not 100% foolproof. Due to the nature of threads, there is no way in Rust to forcibly terminating a thread. So we rely on the thread to be wellbehaved and terminate if asked to do so.

use managed_thread;

// channel to communicate back to main thread
let (tx, rx) = std::sync::mpsc::channel::<()>();
let owned_thread = managed_thread::spawn_owned(move |signal| {
                                while signal.should_continue() {
                                    // do some work
                                }
                                // Send a signal that this thread is exiting
                                tx.send(())
                            });

// The owned thread will now terminate
drop(owned_thread);
// confirm that the managed_thread has terminated
rx.recv().unwrap();

No runtime deps