Locking in PHP (Question for PHP Gurus)

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi All,

I am using PHP on Apache/Linux with mod_php4. I need to implement a
lazy cache for some resource which should be updated say every 1 hour
in a way that the first person who arrives after an hour will be
updating the cache. As you can imagine, I need to implement a write
lock in this case, the idea is:

1. Retrieve the cached data from database (it is cached because
generating it is expensive)
2: If (now() - cache update date) > 1 hour, try to get a lock on some resource
 3.a: If lock is acquired, regenerate the cache, update it in the db,
unlock the resource, return
 3.b: If lock can not be acquired, just display the version retrieved
from cache in step 1 and return
      This will be slightly different in case of mysql (i.e. lock is
blocking in mysql),
      but I guess you get the idea.

In this case, there are two types of locks I can use it looks like:

i)  File locking: You can try to lock a file in non-blocking mode
ii) Use mysql lock/unlock table to manage the locking mechanism, i.e.
create some dummy file.

I would prefer File Locking since it support non-blocking locks and
would definitely be faster than mysql, but I see 2 problems with this:

1. What happens if the php code that locked this file (probably the
PHP thread in Apache, if mod4php supports threading) throws an error
or dies! Will it be automatically unlocked? Or since I am using
mod_php4 and the thread is somehow alive, the lock will be there for a
long time?

2. The following warning from php manual:

 "On some operating systems flock() is implemented at the process
level. When using a multithreaded server API like ISAPI you may not be
able to rely on flock() to protect files against other PHP scripts
running in parallel threads of the same server instance!"


What do you guys recommend?

Thanks!

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux