can we only have one check?

tags: learning programming

content

in the below code, can we remove the first check?

Transclude of double-checked-lock#typical-double-check
in other words, can we have:

with lock:
	if not cache_valid():  # second check
		return refresh_cache()
	return get_cache()
return get_cache()
  • from the perspective of user experience, this works
  • but from the POV of program, this is not optimal, because:
    • now every single thread needs to acquire the lock before reading
    • but in reality, only the thread that needs to refresh the cache will need the lock

up

double-checked-lock

down

reference