如何循环线程句柄并在完成后加入另一个循环?

Blu*_*ue7 3 rust

我有一个程序,它在循环中创建线程,并检查它们是否已完成并清理它们(如果已完成)。请参阅下面的最小示例:

use std::thread;

fn main() {    

    let mut v = Vec::<std::thread::JoinHandle<()>>::new();
    for _ in 0..10 {
        let jh = thread::spawn(|| {
            thread::sleep(std::time::Duration::from_secs(1));
        });
        v.push(jh);
        for jh in v.iter_mut() {
            if jh.is_finished() {
                jh.join().unwrap();
            }
        } 
    }
}
Run Code Online (Sandbox Code Playgroud)

这给出了错误:

error[E0507]: cannot move out of `*jh` which is behind a mutable reference
    --> src\main.rs:13:17
     |
13   |                 jh.join().unwrap();
     |                 ^^^------
     |                 |  |
     |                 |  `*jh` moved due to this method call
     |                 move occurs because `*jh` has type `JoinHandle<()>`, which does not implement the `Copy` trait
     |
note: this function takes ownership of the receiver `self`, which moves `*jh`
    --> D:\rust\.rustup\toolchains\stable-x86_64-pc-windows-msvc\lib/rustlib/src/rust\library\std\src\thread\mod.rs:1461:17
     |
1461 |     pub fn join(self) -> Result<T> {
Run Code Online (Sandbox Code Playgroud)

我怎样才能让借用检查员允许这样做?

Fin*_*nis 6

JoinHandle::join实际上消耗了JoinHandle。 iter_mut()然而,仅借用向量的元素并使向量保持活动状态。因此,您的JoinHandles 只是借用的,并且您不能对借用的对象调用消费方法。

您需要做的是在迭代向量时获取元素的所有权,以便随后可以使用它们join()。这是通过使用into_iter()代替 来实现的iter_mut()

第二个错误是您(可能不小心)将两个for循环编写在彼此内部,而它们应该是独立的循环。

第三个问题稍微复杂一些。您无法检查线程是否已完成,然后按照您的方式加入它。因此我is_finished()暂时取消了检查,并将在下面再次讨论这一点。

这是您的固定代码:

use std::thread;

fn main() {
    let mut v = Vec::<std::thread::JoinHandle<()>>::new();
    for _ in 0..10 {
        let jh = thread::spawn(|| {
            thread::sleep(std::time::Duration::from_secs(1));
        });
        v.push(jh);
    }

    for jh in v.into_iter() {
        jh.join().unwrap();
    }
}
Run Code Online (Sandbox Code Playgroud)

对已完成的线程做出反应

这个比较难。如果您只想等到所有这些都完成,则可以使用上面的代码。

但是,如果您必须立即对已完成的线程做出反应,则基本上必须设置某种事件传播。您不想一遍又一遍地循环所有线程直到它们全部完成,因为这称为空闲等待并消耗大量计算能力。

因此,如果你想实现这一目标,必须解决两个问题:

  • join()消耗JoinHandle(),这会留下不完整VecJoinHandles。这是不可能的,因此我们需要包装JoinHandle一个实际上可以从向量中部分剥离的类型,例如Option.
  • 我们需要一种方法向主线程发出信号,表明新的子线程已完成,以便主线程不必不断迭代线程。

总而言之,实施起来非常复杂且棘手。

这是我的尝试:

use std::{
    thread::{self, JoinHandle},
    time::Duration,
};

fn main() {
    let mut v: Vec<Option<JoinHandle<()>>> = Vec::new();
    let (send_finished_thread, receive_finished_thread) = std::sync::mpsc::channel();

    for i in 0..10 {
        let send_finished_thread = send_finished_thread.clone();

        let join_handle = thread::spawn(move || {
            println!("Thread {} started.", i);

            thread::sleep(Duration::from_millis(2000 - i as u64 * 100));

            println!("Thread {} finished.", i);

            // Signal that we are finished.
            // This will wake up the main thread.
            send_finished_thread.send(i).unwrap();
        });
        v.push(Some(join_handle));
    }

    loop {
        // Check if all threads are finished
        let num_left = v.iter().filter(|th| th.is_some()).count();
        if num_left == 0 {
            break;
        }

        // Wait until a thread is finished, then join it
        let i = receive_finished_thread.recv().unwrap();
        let join_handle = std::mem::take(&mut v[i]).unwrap();
        println!("Joining {} ...", i);
        join_handle.join().unwrap();
        println!("{} joined.", i);
    }

    println!("All joined.");
}
Run Code Online (Sandbox Code Playgroud)

重要的

这段代码只是一个演示。如果其中一个线程发生恐慌,就会出现死锁。但这表明这个问题有多么复杂。

可以通过使用下降防护装置来解决这个问题,但我认为这个答案已经足够复杂了;)