2 unstable releases
0.3.1 | Jan 20, 2024 |
---|---|
0.3.0 |
|
0.2.0 | Jan 20, 2024 |
0.1.1 |
|
0.1.0 |
|
#451 in Concurrency
35 downloads per month
35KB
531 lines
Contains (obscure autoconf code, 1KB) cbits/configure.ac
What is this?
It's just a simple terminatable thread implement with pthread for rust
But Why?
Sometimes, I need to terminate a blocked thread. There is no way to
do it with the standard std::thread
without putting into some Sync
thing.
How to use it?
[dependencies]
terminate-thread = "0.3"
Spawn your thread
use terminate_thread::Thread;
Thread::spawn(|| {}).join(); // ← spawn & join (>= 0.3.0) your thread
Manually terminate your thread
use terminate_thread::Thread;
let thr = Thread::spawn(|| loop {
// infinite loop in this thread
println!("loop run");
std::thread::sleep(std::time::Duration::from_secs(1));
});
std::thread::sleep(std::time::Duration::from_secs(1));
thr.terminate() // ← the thread is terminated manually!
Auto terminate your thread
use terminate_thread::Thread;
{
let _thread = Thread::spawn(|| loop {}); // ← the thread will be terminated when thread is dropped
}
Panic tolerant (v0.3.1, macOS only)
use terminate_thread::Thread;
Thread::spawn(|| panic!()); // ← this is fine
let thread = Thread::spawn(|| panic!("your message")).join(); // ← thread stores the panic info
assert!(thread.over() && thread.panics()); // ← it's over and panics
let info = thread.panic_info().lock().unwrap().take().unwrap(); // ← take out the panic info
assert_eq!(info.downcast_ref::<&str>().unwrap(), &"your message"); // ← get your panic info
Not a good idea!
Terminate a running thread is ALWAYS A BAD IDEA!
The better way is to use something like std::sync::atomic::AtomicBool
,
to give your thread a chance to return.
Tested Platform
- Linux
- macOS
It should work in any platform support pthread,
but the real world is sophisticated to make any promise.
To-do
- Terminate the job which panics. >= v0.3.0
use terminate_thread::Thread;
Thread::spawn(|| panic!()); // ← this is fine
let thread = Thread::spawn(|| panic!()).join(); // ← thread stores the panic info
assert!(thread.over() && thread.panics()); // ← it's over and panics
Issue
- Terminate the thread too quick panics. >= v0.2.0
use terminate_thread::Thread;
Thread::spawn(|| {}); // ← bus error
-
std::panic::AssertUnwindSafe()
does not work in linux. == v0.3.0
use terminate_thread::Thread;
Thread::spawn(|| panic!()); // ← FATAL: exception not rethrown
No runtime deps
~0–2.1MB
~43K SLoC