|
1 | 1 | use libdd_shared_runtime::SharedRuntime; |
2 | 2 | use pyo3::prelude::*; |
3 | 3 | use std::sync::Arc; |
| 4 | +use std::thread; |
4 | 5 | use std::time::Duration; |
5 | 6 |
|
6 | 7 | mod exceptions; |
@@ -43,12 +44,27 @@ impl SharedRuntimePy { |
43 | 44 | .map_err(shared_runtime_error_to_pyerr) |
44 | 45 | } |
45 | 46 |
|
46 | | - fn shutdown(&self, timeout_ms: Option<u64>) -> PyResult<()> { |
| 47 | + fn shutdown(&self, py: Python<'_>, timeout_ms: Option<u64>) -> PyResult<()> { |
47 | 48 | let timeout = timeout_ms.map(Duration::from_millis); |
48 | | - self.inner |
49 | | - .clone() |
50 | | - .shutdown(timeout) |
51 | | - .map_err(shared_runtime_error_to_pyerr) |
| 49 | + let inner = self.inner.clone(); |
| 50 | + let result = py.detach(move || inner.shutdown(timeout)); |
| 51 | + result.map_err(shared_runtime_error_to_pyerr) |
| 52 | + } |
| 53 | + |
| 54 | + fn shutdown_in_thread(&self, py: Python<'_>, timeout_ms: Option<u64>) -> PyResult<()> { |
| 55 | + let timeout = timeout_ms.map(Duration::from_millis); |
| 56 | + let inner = self.inner.clone(); |
| 57 | + // Run shutdown in a dedicated OS thread so that Tokio's `block_on` |
| 58 | + // does not execute on the Python main thread (which avoids conflicts |
| 59 | + // with thread-local Tokio runtime state). We release the GIL while |
| 60 | + // waiting for the thread to join so that other Python threads can |
| 61 | + // continue running during the (potentially slow) shutdown. |
| 62 | + let result = py.detach(move || { |
| 63 | + thread::spawn(move || inner.shutdown(timeout)) |
| 64 | + .join() |
| 65 | + .unwrap_or_else(|_| panic!("SharedRuntime shutdown thread panicked")) |
| 66 | + }); |
| 67 | + result.map_err(shared_runtime_error_to_pyerr) |
52 | 68 | } |
53 | 69 |
|
54 | 70 | fn debug(&self) -> String { |
|
0 commit comments