Skip to content

Commit 8429f31

Browse files
committed
Ensure netcdf4 is locked while closing
1 parent 2b947e9 commit 8429f31

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
@@ -8,7 +8,7 @@
88
from contextlib import AbstractContextManager, contextmanager
99
from typing import Any, Generic, Literal, TypeVar, cast
1010

11-
from xarray.backends.locks import acquire
11+
from xarray.backends.locks import acquire, NETCDF4_PYTHON_LOCK
1212
from xarray.backends.lru_cache import LRUCache
1313
from xarray.core import utils
1414
from xarray.core.options import OPTIONS
@@ -239,6 +239,11 @@ def close(self, needs_lock: bool = True) -> None:
239239
default = None
240240
file = self._cache.pop(self._key, default)
241241
if file is not None:
242+
# Check for string so we do not have to import it
243+
if str(type(file)) == "<class 'netCDF4._netCDF4.Dataset'>":
244+
with NETCDF4_PYTHON_LOCK:
245+
file.close()
246+
return
242247
file.close()
243248

244249
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: Lock | None | Literal[False]) -> 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
@@ -32,6 +32,7 @@
3232
from xarray.backends.locks import (
3333
HDF5_LOCK,
3434
NETCDFC_LOCK,
35+
NETCDF4_PYTHON_LOCK,
3536
combine_locks,
3637
ensure_lock,
3738
get_write_lock,
@@ -66,8 +67,6 @@
6667
# string used by netCDF4.
6768
_endian_lookup = {"=": "native", ">": "big", "<": "little", "|": "native"}
6869

69-
NETCDF4_PYTHON_LOCK = combine_locks([NETCDFC_LOCK, HDF5_LOCK])
70-
7170

7271
class BaseNetCDF4Array(BackendArray):
7372
__slots__ = ("datastore", "dtype", "shape", "variable_name")

0 commit comments

Comments
 (0)