Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Eliminate unnecessary Python reloading which causes memory leaks. #827

Merged
merged 6 commits into from
Jun 29, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 20 additions & 5 deletions pythonmod/pythonmod.c
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,17 @@ log_py_err(void)
Py_XDECREF(exc_tb);
}

/* we only want to unwind Python once at exit */
static void
pythonmod_atexit(void)
{
log_assert(py_mod_count == 0);
log_assert(mainthr != NULL);

PyEval_RestoreThread(mainthr);
Py_Finalize();
}

int pythonmod_init(struct module_env* env, int id)
{
int py_mod_idx = py_mod_count++;
Expand Down Expand Up @@ -310,6 +321,9 @@ int pythonmod_init(struct module_env* env, int id)
#endif
SWIG_init();
mainthr = PyEval_SaveThread();

/* register callback to unwind Python at exit */
atexit(pythonmod_atexit);
}

gil = PyGILState_Ensure();
Expand Down Expand Up @@ -525,6 +539,7 @@ int pythonmod_init(struct module_env* env, int id)

void pythonmod_deinit(struct module_env* env, int id)
{
int cbtype;
struct pythonmod_env* pe = env->modinfo[id];
if(pe == NULL)
return;
Expand All @@ -547,15 +562,15 @@ void pythonmod_deinit(struct module_env* env, int id)
Py_XDECREF(pe->data);
PyGILState_Release(gil);

if(--py_mod_count==0) {
PyEval_RestoreThread(mainthr);
Py_Finalize();
mainthr = NULL;
}
py_mod_count--;
}
pe->fname = NULL;
free(pe);

/* iterate over all possible callback types and clean up each in turn */
for (cbtype = 0; cbtype < inplace_cb_types_total; cbtype++)
inplace_cb_delete(env, cbtype, id);

/* Module is deallocated in Python */
env->modinfo[id] = NULL;
}
Expand Down