ludeed
ludeed

Reputation: 525

How does Rust handle killing threads?

Is there a parent-child connection between threads that are spawned? If I kill the thread from where I spawned other threads, are those going to get killed too? Is this OS specific?

Upvotes: 10

Views: 9762

Answers (1)

Shepmaster
Shepmaster

Reputation: 430524

How does Rust handle killing threads?

It doesn't; there is no way to kill a thread.

See also:

Is there a parent-child connection between threads that are spawned?

When you spawn a thread, you get a JoinHandle that allows you to wait for the child thread to finish. The child does not know of the parent.

[what happens to the other threads] in the context of a thread panicking and dying

The documentation for thread::spawn covers this well:

The join handle will implicitly detach the child thread upon being dropped. In this case, the child thread may outlive the parent (unless the parent thread is the main thread; the whole process is terminated when the main thread finishes). Additionally, the join handle provides a join method that can be used to join the child thread. If the child thread panics, join will return an Err containing the argument given to panic.

That is, once a child thread has been started, what happens to the parent thread basically doesn't matter, unless the parent thread was the main thread, in which case the entire process is terminated.

Upvotes: 14

Related Questions