Skip to content

Commit 28def46

Browse files
committed
Ensure netcdf4 is locked while closing
1 parent 70c3ebf commit 28def46

File tree

3 files changed

+9
-3
lines changed

3 files changed

+9
-3
lines changed

xarray/backends/file_manager.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from collections.abc import Hashable
1010
from typing import Any
1111

12-
from xarray.backends.locks import acquire
12+
from xarray.backends.locks import acquire, NETCDF4_PYTHON_LOCK
1313
from xarray.backends.lru_cache import LRUCache
1414
from xarray.core import utils
1515
from xarray.core.options import OPTIONS
@@ -231,6 +231,11 @@ def close(self, needs_lock=True):
231231
default = None
232232
file = self._cache.pop(self._key, default)
233233
if file is not None:
234+
# Check for string so we do not have to import it
235+
if str(type(file)) == "<class 'netCDF4._netCDF4.Dataset'>":
236+
with NETCDF4_PYTHON_LOCK:
237+
file.close()
238+
return
234239
file.close()
235240

236241
def __del__(self) -> None:

xarray/backends/locks.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -281,3 +281,5 @@ def ensure_lock(lock):
281281
if lock is None or lock is False:
282282
return DummyLock()
283283
return lock
284+
285+
NETCDF4_PYTHON_LOCK = combine_locks([NETCDFC_LOCK, HDF5_LOCK])

xarray/backends/netCDF4_.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
from xarray.backends.locks import (
2626
HDF5_LOCK,
2727
NETCDFC_LOCK,
28+
NETCDF4_PYTHON_LOCK,
2829
combine_locks,
2930
ensure_lock,
3031
get_write_lock,
@@ -58,8 +59,6 @@
5859
# string used by netCDF4.
5960
_endian_lookup = {"=": "native", ">": "big", "<": "little", "|": "native"}
6061

61-
NETCDF4_PYTHON_LOCK = combine_locks([NETCDFC_LOCK, HDF5_LOCK])
62-
6362

6463
class BaseNetCDF4Array(BackendArray):
6564
__slots__ = ("datastore", "dtype", "shape", "variable_name")

0 commit comments

Comments
 (0)