summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMatthias Geier <Matthias.Geier@gmail.com>2016-11-02 18:49:04 +0100
committerMatthias Geier <Matthias.Geier@gmail.com>2016-11-02 20:15:29 +0100
commite5a6c3b8a2182767735ad259cfc789f85715c89c (patch)
treebc5e114d55a4c0d07b2a4d65a035b4eac865c648
parente791adfadfaf8562203acbc177cb4aef342fce84 (diff)
Fix "atexit" handling
atexit.unregister() removes all instances of the registered function, not only one, therefore nested calls didn't work like they are supposed to. See http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html and https://docs.python.org/3/library/atexit.html#atexit.unregister. This commit fixes #47, which was the real reason for the change, since atexit.unregister() doesn't even exist in Python 2.
-rw-r--r--sounddevice.py14
1 files changed, 12 insertions, 2 deletions
diff --git a/sounddevice.py b/sounddevice.py
index 8a43b5e..41e93d9 100644
--- a/sounddevice.py
+++ b/sounddevice.py
@@ -336,6 +336,7 @@ _sampleformats = {
'uint8': _lib.paUInt8,
}
+_initialized = 0
_last_callback = None
@@ -2672,14 +2673,22 @@ def _get_device_id(id_or_query_string, kind, raise_on_error=False):
def _initialize():
"""Initialize PortAudio."""
+ global _initialized
_check(_lib.Pa_Initialize(), 'Error initializing PortAudio')
- _atexit.register(_lib.Pa_Terminate)
+ _initialized += 1
def _terminate():
"""Terminate PortAudio."""
- _atexit.unregister(_lib.Pa_Terminate)
+ global _initialized
_check(_lib.Pa_Terminate(), 'Error terminating PortAudio')
+ _initialized -= 1
+
+
+def _exit_handler():
+ assert _initialized >= 0
+ while _initialized:
+ _terminate()
def _ignore_stderr():
@@ -2707,6 +2716,7 @@ def _ignore_stderr():
_ignore_stderr()
+_atexit.register(_exit_handler)
_initialize()
if __name__ == '__main__':