use std::sync::{Mutex, PoisonError, Weak};
use pyo3::prelude::*;
pub(crate) fn run_attached(thread: rayon::ThreadBuilder) {
let mut thread = Some(thread);
Python::try_attach(|py| py.detach(|| thread.take().map(rayon::ThreadBuilder::run)));
if let Some(thread) = thread {
thread.run();
}
}
static POOLS: Mutex<Vec<Weak<rayon::ThreadPool>>> = Mutex::new(Vec::new());
pub(crate) fn track(pool: Weak<rayon::ThreadPool>) {
let mut pools = POOLS.lock().unwrap_or_else(PoisonError::into_inner);
pools.retain(|p| p.strong_count() > 0);
if !pools.iter().any(|p| p.ptr_eq(&pool)) {
pools.push(pool);
}
}
#[pyfunction]
#[pyo3(name = "_keep_pools_alive")]
pub(crate) fn keep_pools_alive() {
let pools = std::mem::take(&mut *POOLS.lock().unwrap_or_else(PoisonError::into_inner));
for pool in pools.iter().filter_map(Weak::upgrade) {
std::mem::forget(pool);
}
}