|
12 | 12 | import numpy as np |
13 | 13 |
|
14 | 14 | from .. import __version__ as MNE_VERSION # ty: ignore[unresolved-import] |
15 | | -from ..utils import _soft_import, get_config, logger |
| 15 | +from ..utils import get_config, logger |
16 | 16 |
|
17 | 17 | _RAW_PRELOAD_CACHE_VERSION = 1 |
18 | | -_RAW_PRELOAD_LOCK_TIMEOUT = 300.0 |
19 | 18 |
|
20 | 19 |
|
21 | 20 | def _raw_preload_cache_info(raw): |
@@ -82,27 +81,29 @@ def _raw_preload_auto(raw): |
82 | 81 | logger.info(f"Reusing decoded data from {path}") |
83 | 82 | return data |
84 | 83 |
|
85 | | - # Importing filelock is measurable, so keep it off the cache-hit path. |
86 | | - filelock = _soft_import("filelock", "locking the decoded-data cache") |
87 | | - with filelock.FileLock(f"{path}.lock", timeout=_RAW_PRELOAD_LOCK_TIMEOUT): |
88 | | - data = _raw_preload_cache_read(path, shape, dtype) |
89 | | - if data is None: |
90 | | - logger.info(f"Creating decoded data cache in {path.parent}") |
91 | | - temporary = path.with_suffix(".tmp") |
92 | | - try: |
93 | | - temporary.unlink(missing_ok=True) |
94 | | - data = np.memmap(temporary, mode="w+", dtype=dtype, shape=shape) |
95 | | - try: |
96 | | - raw._read_segment(data_buffer=data) |
97 | | - data.flush() |
98 | | - finally: |
99 | | - data._mmap.close() # ty: ignore[unresolved-attribute] |
100 | | - if _raw_preload_cache_info(raw)[1] != sources: |
101 | | - raise RuntimeError( |
102 | | - "Source data changed while decoded cache was created; retry" |
103 | | - ) |
104 | | - os.replace(temporary, path) |
105 | | - finally: |
106 | | - temporary.unlink(missing_ok=True) |
107 | | - data = _raw_preload_cache_read(path, shape, dtype) |
| 84 | + # The temporary is per-process and os.replace is atomic, so concurrent |
| 85 | + # misses need no lock; they at worst decode the same entry twice. |
| 86 | + logger.info(f"Creating decoded data cache in {path.parent}") |
| 87 | + temporary = path.with_suffix(f".{os.getpid()}.tmp") |
| 88 | + try: |
| 89 | + data = np.memmap(temporary, mode="w+", dtype=dtype, shape=shape) |
| 90 | + try: |
| 91 | + raw._read_segment(data_buffer=data) |
| 92 | + data.flush() |
| 93 | + finally: |
| 94 | + data._mmap.close() # ty: ignore[unresolved-attribute] |
| 95 | + if _raw_preload_cache_info(raw)[1] != sources: |
| 96 | + raise RuntimeError( |
| 97 | + "Source data changed while decoded cache was created; retry" |
| 98 | + ) |
| 99 | + try: |
| 100 | + os.replace(temporary, path) |
| 101 | + except OSError: |
| 102 | + # Windows refuses to replace an entry another process already mapped. |
| 103 | + pass |
| 104 | + finally: |
| 105 | + temporary.unlink(missing_ok=True) |
| 106 | + data = _raw_preload_cache_read(path, shape, dtype) |
| 107 | + if data is None: |
| 108 | + raise RuntimeError(f"Could not read back the decoded data cache at {path}") |
108 | 109 | return data |
0 commit comments