Skip to content

Commit d3d0b69

Browse files
committed
Lock the cache directory
In case multiple processes use it at the same time. Don't delete the lock file in expire().
1 parent e4dc4da commit d3d0b69

File tree

1 file changed

+25
-21
lines changed

1 file changed

+25
-21
lines changed

lib/matplotlib/testing/conversion_cache.py

Lines changed: 25 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -89,12 +89,13 @@ def get(self, filename, newname):
8989
self.gets.add(filename)
9090
hash_value = self._get_file_hash(filename)
9191
cached_file = os.path.join(self.cachedir, hash_value + self.cached_ext)
92-
if os.path.exists(cached_file):
93-
shutil.copyfile(cached_file, newname)
94-
self.hits.add(filename)
95-
return True
96-
else:
97-
return False
92+
with cbook.Locked(self.cachedir):
93+
if os.path.exists(cached_file):
94+
shutil.copyfile(cached_file, newname)
95+
self.hits.add(filename)
96+
return True
97+
else:
98+
return False
9899

99100
def put(self, original, converted):
100101
"""Insert a file into the cache.
@@ -108,7 +109,8 @@ def put(self, original, converted):
108109
"""
109110
hash_value = self._get_file_hash(original)
110111
cached_file = os.path.join(self.cachedir, hash_value + self.cached_ext)
111-
shutil.copyfile(converted, cached_file)
112+
with cbook.Locked(self.cachedir):
113+
shutil.copyfile(converted, cached_file)
112114

113115
def _get_file_hash(self, path, block_size=2 ** 20):
114116
if path in self.hash_cache:
@@ -150,20 +152,22 @@ def expire(self):
150152
Orders files by access time, so the least recently used files
151153
get deleted first.
152154
"""
153-
stats = {filename: os.stat(os.path.join(self.cachedir, filename))
154-
for filename in os.listdir(self.cachedir)}
155-
usage = sum(f.st_size for f in stats.values())
156-
to_free = usage - self.max_size
157-
if to_free <= 0:
158-
return
159-
160-
files = sorted(os.listdir(self.cachedir),
161-
key=lambda f: stats[f].st_atime,
162-
reverse=True)
163-
while to_free > 0:
164-
filename = files.pop()
165-
os.remove(os.path.join(self.cachedir, filename))
166-
to_free -= stats[filename].st_size
155+
with cbook.Locked(self.cachedir):
156+
stats = {filename: os.stat(os.path.join(self.cachedir, filename))
157+
for filename in os.listdir(self.cachedir)
158+
if filename.endswith(self.cached_ext)}
159+
usage = sum(f.st_size for f in stats.values())
160+
to_free = usage - self.max_size
161+
if to_free <= 0:
162+
return
163+
164+
files = sorted(stats.keys(),
165+
key=lambda f: stats[f].st_atime,
166+
reverse=True)
167+
while to_free > 0:
168+
filename = files.pop()
169+
os.remove(os.path.join(self.cachedir, filename))
170+
to_free -= stats[filename].st_size
167171

168172
@staticmethod
169173
def get_cache_dir():

0 commit comments

Comments
 (0)