Skip to content

Commit 882ca92

Browse files
AndreasKaratzashunterhogan
authored andcommitted
Factor out openfunction to dedupe lock+error handling
1 parent 9ced432 commit 882ca92

1 file changed

Lines changed: 10 additions & 17 deletions

File tree

soundfile.py

Lines changed: 10 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1314,7 +1314,7 @@ def close(self) -> None:
13141314
# sf_error(NULL) to retrieve the error code, but another thread
13151315
# may clear the global error between our open and our sf_error.
13161316
# This lock serialises the open+sf_error(NULL) pair to prevent that.
1317-
_open_lock = _threading.Lock()
1317+
_sf_error_lock = _threading.Lock()
13181318

13191319
def _open(self, file, mode_int, closefd):
13201320
"""Call the appropriate sf_open*() function from libsndfile."""
@@ -1331,26 +1331,19 @@ def _open(self, file, mode_int, closefd):
13311331
openfunction = _snd.sf_wchar_open
13321332
else:
13331333
file = file.encode(_sys.getfilesystemencoding())
1334-
with self._open_lock:
1335-
file_ptr = openfunction(file, mode_int, self._info)
1336-
if file_ptr == _ffi.NULL:
1337-
err = _snd.sf_error(file_ptr)
1338-
raise LibsndfileError(err, prefix="Error opening {0!r}: ".format(self.name))
13391334
elif isinstance(file, int):
1340-
with self._open_lock:
1341-
file_ptr = _snd.sf_open_fd(file, mode_int, self._info, closefd)
1342-
if file_ptr == _ffi.NULL:
1343-
err = _snd.sf_error(file_ptr)
1344-
raise LibsndfileError(err, prefix="Error opening {0!r}: ".format(self.name))
1335+
openfunction = lambda file, mode_int, info: _snd.sf_open_fd(file, mode_int, info, closefd)
13451336
elif _has_virtual_io_attrs(file, mode_int):
1346-
with self._open_lock:
1347-
file_ptr = _snd.sf_open_virtual(self._init_virtual_io(file),
1348-
mode_int, self._info, _ffi.NULL)
1349-
if file_ptr == _ffi.NULL:
1350-
err = _snd.sf_error(file_ptr)
1351-
raise LibsndfileError(err, prefix="Error opening {0!r}: ".format(self.name))
1337+
openfunction = lambda file, mode_int, info: _snd.sf_open_virtual(self._init_virtual_io(file),
1338+
mode_int, info, _ffi.NULL)
13521339
else:
13531340
raise TypeError("Invalid file: {0!r}".format(self.name))
1341+
1342+
with self._sf_error_lock:
1343+
file_ptr = openfunction(file, mode_int, self._info)
1344+
if file_ptr == _ffi.NULL:
1345+
err = _snd.sf_error(file_ptr)
1346+
raise LibsndfileError(err, prefix="Error opening {0!r}: ".format(self.name))
13541347
if mode_int == _snd.SFM_WRITE:
13551348
# Due to a bug in libsndfile version <= 1.0.25, frames != 0
13561349
# when opening a named pipe in SFM_WRITE mode.

0 commit comments

Comments
 (0)