首页 > 解决方案 > 当进程终止时,如何在阻塞子线程中执行清理?

问题描述

我有以下人为的 Rust 代码:

use std::thread;

const THREAD_COUNT: u8 = 10;

struct DropMe {
    id: u8,
}

impl Drop for DropMe {
    fn drop(&mut self) {
        println!("Dropped item {}", self.id);
    }
}

fn main() {
    let outer_drop_me = DropMe { id: 255 };
    println!(
        "Created instance outside of threads with ID: {}",
        &outer_drop_me.id
    );
    for i in 0..THREAD_COUNT {
        let drop_me = DropMe { id: i };
        thread::spawn(move || {
            println!("Spawned thread {}", drop_me.id);
            // Poor man's substitute for illustrating blocking I/O
            thread::sleep(std::time::Duration::from_millis(500));
            // Poor man's substitute for illustrating a cleanup function
            drop(drop_me);
        });
    }
    // outer_drop_me should be dropped automatically here as it goes out of
    // scope
}

其输出如下:

Created instance outside of threads with ID: 255
Spawned thread 0
Spawned thread 1
Spawned thread 2
Spawned thread 3
Spawned thread 4
Spawned thread 5
Spawned thread 6
Spawned thread 7
Spawned thread 8
Dropped item 255
Spawned thread 9

如何在线程中的代码可能被阻塞但进程被终止(例如通过SIGTERM)的线程中进行清理?

在这个人为设计的例子中,我们可以join在派生线程返回的线程句柄上,但是如果join不可用并且子线程阻塞怎么办?您是否只是在可能阻塞的代码部分之后放弃清理代码?

标签: multithreadingrust

解决方案


推荐阅读