use alloc::vec::Vec;
use super::id::{ProcId, ThreadId};
#[cfg(feature = "thread")]
pub struct ProcThreadRel {
pub parent: ProcId,
pub children: Vec<ProcId>,
pub dead_children: Vec<(ProcId, isize)>,
pub threads: Vec<ThreadId>,
pub dead_threads: Vec<(ThreadId, isize)>,
}
impl ProcThreadRel {
pub fn new(parent_pid: ProcId) -> Self {
Self {
parent: parent_pid,
children: Vec::new(),
dead_children: Vec::new(),
threads: Vec::new(),
dead_threads: Vec::new(),
}
}
pub fn add_child(&mut self, child_pid: ProcId) {
self.children.push(child_pid);
}
pub fn del_child(&mut self, child_pid: ProcId, exit_code: isize) {
let pair = self
.children
.iter()
.enumerate()
.find(|&(_, &id)| id == child_pid);
if let Some((idx, _)) = pair {
let dead_child = self.children.remove(idx);
self.dead_children.push((dead_child, exit_code));
}
}
pub fn wait_any_child(&mut self) -> Option<(ProcId, isize)> {
if self.dead_children.is_empty() {
if self.children.is_empty() {
None
} else {
Some((ProcId::from_usize(-2 as _), -1))
}
} else {
self.dead_children.pop()
}
}
pub fn wait_child(&mut self, child_pid: ProcId) -> Option<(ProcId, isize)> {
let pair = self
.dead_children
.iter()
.enumerate()
.find(|&(_, &(id, _))| id == child_pid);
if let Some((idx, _)) = pair {
Some(self.dead_children.remove(idx))
} else {
let pair = self
.children
.iter()
.enumerate()
.find(|&(_, &id)| id == child_pid);
if let Some(_) = pair {
Some((ProcId::from_usize(-2 as _), -1))
} else {
None
}
}
}
pub fn add_thread(&mut self, tid: ThreadId) {
self.threads.push(tid);
}
pub fn del_thread(&mut self, tid: ThreadId, exit_code: isize) {
let pair = self.threads.iter().enumerate().find(|&(_, &id)| id == tid);
if let Some((idx, _)) = pair {
let dead_thread = self.threads.remove(idx);
self.dead_threads.push((dead_thread, exit_code));
}
}
pub fn wait_thread(&mut self, thread_tid: ThreadId) -> Option<isize> {
let pair = self
.dead_threads
.iter()
.enumerate()
.find(|&(_, &(id, _))| id == thread_tid);
if let Some((idx, _)) = pair {
Some(self.dead_threads.remove(idx).1)
} else {
let pair = self
.threads
.iter()
.enumerate()
.find(|&(_, &id)| id == thread_tid);
if let Some(_) = pair {
Some(-2)
} else {
None
}
}
}
}