terminate-thread

Crates.ioterminate-thread
lib.rsterminate-thread
version0.3.1
created_at2024-01-20 09:50:24.567576+00
updated_at2024-01-20 18:16:11.350536+00
descriptionA simple terminatable thread implemented with pthread
homepage
repositoryhttps://github.com/uuhan/terminate-thread
max_upload_size
id1106376
size50,834
uuhan (uuhan)

documentation

README

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
Commit count: 25

cargo fmt