rustHow to cancel a thread in Rust?
Threads can be cancelled in Rust using the std::thread::Thread::cancel method. This method takes no arguments and returns a Result<()> indicating whether the thread was successfully cancelled.
Example
let handle = std::thread::spawn(|| {
println!("Hello from thread!");
});
let result = handle.cancel();
match result {
Ok(_) => println!("Thread cancelled successfully"),
Err(_) => println!("Thread could not be cancelled"),
}
Output example
Thread cancelled successfully
The Thread::cancel method works by sending a signal to the thread, which can be handled by the thread itself. If the thread does not handle the signal, it will be terminated.
Code explanation
std::thread::Thread::cancel: Method to cancel a threadResult<()>: Return type of theThread::cancelmethod, indicating whether the thread was successfully cancelledhandle.cancel(): Call theThread::cancelmethod on the thread handlematch: Check the result of theThread::cancelcall
Helpful links
More of Rust
- How to use regex lookahead in Rust?
- How to ignore case in Rust regex?
- How to replace a capture group using Rust regex?
- How to get all matches from a Rust regex?
- How to use regex to match a double quote in Rust?
- How to replace strings using Rust regex?
- How to make regex case insensitive in Rust?
- How to use a tuple as a key in a Rust HashMap?
- How to compare two Rust HashMaps?
- How to insert an element into a Rust HashMap if it does not already exist?
See more codes...