Skip to content

Commit

Permalink
amrex::Finalize() w/ gc.collect() (#83)
Browse files Browse the repository at this point in the history
When calling `amrex.finalize()`, first call the Python
garbage collector. This is purely a bandage to make
usage like this easy:

```py
import amrex

amrex.initialize([])
mfab = amrex.MultiFab( ... )
del mfab
amrex.finalize()
```

Respect the Python standard guarantees without furhter headache,
by running an explicit call to the garbage collector.

Previously, this was only working with CPython, but alternative
implementations like PyPy might delay the true free due to time
based memory collection approaches.
  • Loading branch information
ax3l authored Oct 17, 2022
1 parent aa683b9 commit 86273bd
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions src/Base/AMReX.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,25 @@ void init_AMReX(py::module& m)
}, py::return_value_policy::reference,
"Initialize AMReX library");

constexpr auto run_gc = []() {
// explicitly run the garbage collector, so deleted objects
// get freed.
// This is a convenience helper/bandage for making work with Python
// garbage collectors in various implementations more easy.
// https://github.com/AMReX-Codes/pyamrex/issues/81
auto m_gc = py::module::import("gc");
auto collect = m_gc.attr("collect");
collect();
};

m.def("finalize",
[run_gc]() {
run_gc();
amrex::Finalize();
});
m.def("finalize",
py::overload_cast<>(&Finalize));
m.def("finalize", py::overload_cast<AMReX*>(&Finalize));
[run_gc](AMReX* pamrex) {
run_gc();
amrex::Finalize(pamrex);
});
}

0 comments on commit 86273bd

Please sign in to comment.