| Crates.io | terminate-thread |
| lib.rs | terminate-thread |
| version | 0.3.1 |
| created_at | 2024-01-20 09:50:24.567576+00 |
| updated_at | 2024-01-20 18:16:11.350536+00 |
| description | A simple terminatable thread implemented with pthread |
| homepage | |
| repository | https://github.com/uuhan/terminate-thread |
| max_upload_size | |
| id | 1106376 |
| size | 50,834 |
It's just a simple terminatable thread implement with pthread for rust
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.
[dependencies]
terminate-thread = "0.3"
use terminate_thread::Thread;
Thread::spawn(|| {}).join(); // ← spawn & join (>= 0.3.0) 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!
use terminate_thread::Thread;
{
let _thread = Thread::spawn(|| loop {}); // ← the thread will be terminated when thread is dropped
}
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
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.
It should work in any platform support pthread,
but the real world is sophisticated to make any promise.
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
use terminate_thread::Thread;
Thread::spawn(|| {}); // ← bus error
std::panic::AssertUnwindSafe() does not work in linux. == v0.3.0use terminate_thread::Thread;
Thread::spawn(|| panic!()); // ← FATAL: exception not rethrown