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::cancel
method, indicating whether the thread was successfully cancelledhandle.cancel()
: Call theThread::cancel
method on the thread handlematch
: Check the result of theThread::cancel
call
Helpful links
More of Rust
- How to get a capture group using Rust regex?
- How to use regex to match a double quote in Rust?
- How to use regex with bytes in Rust?
- How to match whitespace with a regex in Rust?
- How to implement PartialEq for a Rust HashMap?
- How to replace strings using Rust regex?
- How to parse JSON string in Rust?
- How to use regex to match a group in Rust?
- How to calculate the inverse of a matrix in Rust?
- How to insert an element into a Rust HashMap if it does not already exist?
See more codes...