Re: Is flock necessary?
| From: | Alan McFarlane | Date: | Thu, 07 Mar 2002 11:55:21 +0000 |
| Subject: | Re: Is flock necessary? | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-87606@lists.php.net to get a copy of this message | ||
flock() may not be required - but I'm pretty sure it's damn sensible. As for
using mySQL, well, these routines are part of a simple file-based cache
system (specifically in my case used for caching mySQL data)
Jtjohnston <taylorjo@collegesherbrooke.qc.ca> wrote in message
news:3C86F290.550B957B@collegesherbrooke.qc.ca...
> Group: Is flock even necessary?
> Allan: You look like you have Perled. It was necessary for Perl.
> Have you thought of MySQL instead?
>
>
> Alan McFarlane wrote:
>
> > I've just written a couple of simple routines which read an write small
text
> > files to the server:
> >
> > function readData( $filename, &$data )
> > {
> > if (!$fd = @fopen($filename, "r"))
> > {
> > return false;
> > }
> >
> > flock($fd, LOCK_SH);
> > $data = fread($fd, filesize($filename));
> > fclose($fd);
> >
> > return true;
> > }
> >
> > function writeData( $filename, $data )
> > {
> > if (!$fd = @fopen($filename, "w"))
> > {
> > return false;
> > }
> >
> > flock($fd, LOCK_EX);
> > fwrite($fd, $data);
> > fclose($fd);
> >
> > return true;
> > }
> >
> > Now, the question is... How much time elapses between the fopen()
statement
> > and the flock() statements?
> >
> > Looking at the code, it would appear that two separate threads may call
> > writeData() almost simultaneously giving the following execution:
> >
> > assume $filename = "sample.txt";
> >
> > Thread #1 - $fd = fopen($filename, "w"); // succeeds
> > Thread #2 - $fd = fopen($filename, "w"); // succeeds (I think)
> > Thread #1 - flock($fd, LOCK_EX); // Does this succeed or fail?
> > Thread #2 - flock($fd, LOCK_EX); // fails (I think)
>
> --
> John Taylor-Johnston
> --------------------------------------------------------------------------
---
> ' ' ' Collège de Sherbrooke:
> ô¿ô http://www.collegesherbrooke.qc.ca/languesmodernes/
> - Université de Sherbrooke:
> http://compcanlit.ca/
> 819-569-2064
>
>