From 55bbb9fcab0d6d2b45b00c3a46a892739b2c5a4d Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Sat, 23 May 2020 21:58:46 +0200 Subject: [PATCH] Call Py_Finalize at exit using libc::atexit. This makes sure buffers are flushed, threads are joined, etc. when exiting the process. --- src/gil.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/gil.rs b/src/gil.rs index 7c333da2e5c..ec3666e8512 100644 --- a/src/gil.rs +++ b/src/gil.rs @@ -83,7 +83,12 @@ pub fn prepare_freethreaded_python() { // PyPy does not support the embedding API #[cfg(not(PyPy))] - ffi::Py_InitializeEx(0); + { + ffi::Py_InitializeEx(0); + + // Make sure Py_Finalize will be called before exiting. + libc::atexit(finalize); + } // > Changed in version 3.7: This function is now called by Py_Initialize(), so you don’t have // > to call it yourself anymore. @@ -356,6 +361,15 @@ fn decrement_gil_count() { }) } +extern "C" fn finalize() { + unsafe { + if ffi::Py_IsInitialized() != 0 { + ffi::PyGILState_Ensure(); + ffi::Py_Finalize(); + } + } +} + #[cfg(test)] mod test { use super::{gil_is_acquired, GILPool, GIL_COUNT, OWNED_OBJECTS, POOL};