Skip to content

Commit

Permalink
Call Py_Finalize at exit using libc::atexit.
Browse files Browse the repository at this point in the history
This makes sure buffers are flushed, threads are joined, etc. when
exiting the process.
  • Loading branch information
m-ou-se committed May 23, 2020
1 parent 072be6c commit 55bbb9f
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/gil.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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};
Expand Down

0 comments on commit 55bbb9f

Please sign in to comment.