根据预先定义的预设,您可以根据请求调整图像大小,然后将其附加到已调整大小的图像文件名,并保存在同一目录中。在调整大小期间,如果两个请求拉动相同的图像,您如何处理竞争条件?
建议的解决方案是:
import os
import time
import my_threadsafe_cache_module as cache
from my_image_resizer import resize_by_preset_name
def resize_on_demand(preset, original_image_filepath, *args, **kwargs):
"""
Args:
preset: A string containing the name of your pre-defined preset.
original_image_filepath: A string containing the original filepath.
args, kwargs: Passed to resize_by_preset_name
"""
resized_filename = ('_' + preset).join(os.path.splitext(original_image_filepath))
if os.path.exists(resized_filename):
return resized_filename
# If the image does not exist, we shall create the resized version.
cache_key = cache.get('RESIZE_' + resized_filename) # Should return None or True
if cache_key is None:
try: # Ensure that the cache key is always deleted
cache.set('RESIZE_' + resized_filename, True, 5) # 5 indicates seconds
resize_by_preset_name(preset, original_image_filepath, *args, **kwargs)
finally:
cache.delete('RESIZE_' + resized_filename) # Delete the cache key
else: # We wait until cache_key is not None
while cache_key is not None:
time.sleep(1)
cache_key = cache.get('RESIZE_' + resized_filename)
return resized_filename
这是正确的做法吗?什么可能陷阱?