Fix segfaults from releasing the GIL in Python 3
This fixes several segfaults that happen when running with Python 3.9. See https://gitlab.cern.ch/-/snippets/1824 for a small collection of unit tests that I wrote to find these, as well as details on how to reproduce the issues.