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 use regex with bytes in Rust?
- How to match a URL with a regex in Rust?
- How to use regex to match a double quote in Rust?
- How to replace a capture group using Rust regex?
- How to perform matrix operations in Rust?
- How to convert a Rust slice of u8 to a string?
- How do I copy a variable in Rust?
- How to parse a file with Rust regex?
- How to match the end of a line in a Rust regex?
- How to clear a Rust HashMap?
See more codes...