multithreading - 有没有办法在 Rust 中生成具有指定生命周期的线程?

标签 multithreading rust

这个问题在这里已经有了答案:





How can I pass a reference to a stack variable to a thread?

(1 个回答)


1年前关闭。




我对 Rust 很陌生,所以我遇到了一些我不习惯的事情。一个让我感到悲伤的问题与线程有关。
我想生成一个执行结构方法的线程,但我不能,因为该方法需要有一个 'static生命周期。我更喜欢没有 'static 的方法(以及扩展的结构)生命周期。
如果我确定线程将在结构的实例化值被删除之前退出,有没有办法与 Rust 进行通信?换句话说,我可以告诉 Rust 我可以保证在线程退出之前不会删除该值吗?或者也许有办法将生命传递给线程?
如果这一切都不可能,那么可以做些什么呢?我已经研究过使代码异步,但在解决上述问题方面没有任何成功。
如果方法和结构必须有 'static一生,我该如何适本地指定这一点?
这是问题的简化示例:

pub struct Thing {
    value: i32,
}

impl Thing {
    pub fn new(value: i32) -> Thing {
        Thing {
            value,
        }
    }

    fn in_thread(&self) {
        println!("in thread");
        // do things that block the thread
    }

    pub fn spawn_thread(&self) {
        std::thread::spawn(move || {
            self.in_thread();           // problem occurs here
        });
    }
}

最佳答案

If none of this is possible, what can be done instead? I've looked into making the code asynchronous instead, but haven't had any success in fixing the issues described above.


我不建议通过对其他线程的引用来传递数据。相反,尝试设计您的程序,以便线程可以拥有数据。您可以通过在生成线程时移入数据来做到这一点,或者,您可能希望通过 Channel 传递数据。 .

关于multithreading - 有没有办法在 Rust 中生成具有指定生命周期的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63973025/

相关文章:

java - 为什么我遇到同步问题?

linux - 如何在 Linux 下从特定接口(interface)发送 UDP 数据包?

rust - 如何对不直接使用该类型的结构进行类型参数化?

rust - 我如何获得一个函数来返回类似字符串的 Vec?

rust - 收集后Vec变异性不匹配

java - Guava 事件总线 : NullPointerException when Posting from Thread to UI

multithreading - 是否准确地说每个响应输入的程序都有一个无限循环的主线程?

c++ - 登录多线程的最佳实践是什么?

java - 在工作线程中读取 GUI 对象数据

rust - Rust 中有队列和堆栈集合吗?