How does Rust handle killing threads?

2019-08-29 11:40发布

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?

1条回答
劳资没心,怎么记你
2楼-- · 2019-08-29 12:23

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.

查看更多
登录 后发表回答