I'll assume the lock_retrieve() and lock_nstore() both obtain a lock and then operate on the cachefile.
First off, you have some problematic races. There is one between -e $lockfile and open (LOCK, ">$lockfile"); where multiple script instances can fall through to the non-cached path (and then sequentially update the cache file).
Secondly, I think there's a race between close LOCK and unlink $lockfile. After the close, another process can obtain the lockfile, only for this to be promptly deleted, allowing a third process to grab the lock as well...
Thirdly, the locking will needlessly hinder cached reads when it happens.
Now about the fix. 1) Open the cache-file. 2) Stat the open file. 3) If age is less than 2*thresh, use the cached content. 4) If age is more than 1*thresh, trigger $update_needed. 5) When update is needed, launch the updater, or, if access delays are acceptable, perform the locked-update right there. 6) The updater can LOCK_EX|LOCK_NB the cache file, write a new tmpfile and rename that. Coded this way, the cached fast path needs no locking at all. HtH.
Edit. added LOCK_NB above, probably the simplest way to ensure a single updater is run. flock+fork should be acceptable for running the update.
In reply to Re: Faster locking
by oiskuu
in thread Faster locking
by bbs2web
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |