multithreading - 当进程终止时,如何在阻塞子线程中执行清理?
问题描述
我有以下人为的 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
不可用并且子线程阻塞怎么办?您是否只是在可能阻塞的代码部分之后放弃清理代码?
解决方案
推荐阅读
- python - tkinter:使用标签突出显示文本的取消突出显示
- java - 运行 jol-core 异常,异常消息是“进程完成,退出代码 137(被信号 9 中断:SIGKILL)”
- java - 带有 SQL Workbench 的 postgreSQL:不支持从日期开始的类 java.time.LocalDate
- php - 不能使用类名类型的对象作为数组错误
- java - RxAndroidBle 多特征通知
- python - django-summernote 在 Django 管理页面上不可编辑
- passport.js - NestJS Fastify 身份验证
- java - 给定 spring-webflux 中的请求,是否可以以编程方式解析可生产的内容类型?
- saas - 如何根据全局变量获取业务中心页面字段的值
- python - 登录后使用请求下载运行时文件