I find myself writing my first C extension module, which is a fun experience mostly. Sadly, Baby’s First Module is complicated by starting up a background thread to run I²C communications (no, running the I²C comms in foreground is not an option). So far I have things communicating back and forth safely across the thread divide, reference counting is only normally nightmarish, the usual stuff.
However I have a problem when exiting test scripts. I would very much like some kind of module finalization hook so that I can shut down the comms thread before the Python interpreter tears down the infrastructure that the thread relies on for communicating with the foreground. As my module stands, it is possible for a badly timed message from the far end to invoke code that is no longer expecting to be called; this appears to happen in practise since my colleague can get SIGSEGV about 50% of the time with a simple test script.
Aside from mentioning that dynamically loaded modules are not unloaded, the fulsome documentation on writing extension modules drops no hints about module finalization. Is there any hook I can tap into, or am I doomed to need an explicit shutdown function?
(I practice I don’t think this is a big deal; the tests are artificially engineering bad timing which is much less likely to happen in real life. It does however offend my soul to end with a segfault if I don’t need to.)