如何在Rust中检查线程是否完成? [英] How to check if a thread has finished in Rust?

查看:298
本文介绍了如何在Rust中检查线程是否完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在Rust中使用spawn线程时,会得到一个JoinHandle,这对于...连接(阻塞操作)非常有用,而其他功能不多.如何检查子线程是否已从父线程退出(即JoinHandle.join()不会阻塞)?如果您知道如何杀死子线程,将获得加分.

When I spawn a thread in Rust, I get a JoinHandle, which is good for... joining (a blocking operation), and not much else. How can I check if a child thread has exited (i.e., JoinHandle.join() would not block) from the parent thread? Bonus points if you know how to kill a child thread.

我想您可以通过创建一个频道,向孩子发送一些东西并捕获错误来做到这一点,但这似乎是不必要的复杂性和开销.

I imagine you could do this by creating a channel, sending something to the child, and catching errors, but that seems like needless complexity and overhead.

推荐答案

从Rust 1.7开始,标准库中没有API可以检查子线程是否已经退出而没有阻塞.

As of Rust 1.7, there's no API in the standard library to check if a child thread has exited without blocking.

一种可移植的解决方法是使用频道发送一个从孩子到父母的消息,表明孩子即将退出. Receiver 具有非阻塞<一个href ="http://doc.rust-lang.org/stable/std/sync/mpsc/struct.Receiver.html#method.try_recv" rel ="noreferrer"> try_recv 方法.当try_recv确实收到消息时,您可以在JoinHandle上使用join()检索线程的结果.

A portable workaround would be to use channels to send a message from the child to the parent to signal that the child is about to exit. Receiver has a non-blocking try_recv method. When try_recv does receive a message, you can then use join() on the JoinHandle to retrieve the thread's result.

还存在不稳定的特定于平台的扩展特征,可让您获取原始线程句柄.然后,您必须编写平台特定的代码来测试线程是否退出.

There are also unstable platform-specific extension traits that let you obtain the raw thread handle. You'd then have to write platform-specific code to test whether the thread has exited or not.

如果您认为此功能应该在Rust的标准库中,则可以提交RFC (请务必先阅读自述文件!).

If you think this feature should be in Rust's standard library, you can submit an RFC (be sure to read the README first!).

如果您知道如何杀死子线程,则奖励积分.

Bonus points if you know how to kill a child thread.

Rust中的线程是使用本机OS线程实现的.即使操作系统可能提供了一种杀死线程的方法,这样做也是一个坏主意,因为在进程结束.

Threads in Rust are implemented using native OS threads. Even though the operating system might provide a way to kill a thread, it's a bad idea to do so, because the resources that the thread allocated will not be cleaned up until the process ends.

这篇关于如何在Rust中检查线程是否完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆