我想要一个不时更新的临时文件。我当时想做的是:
<!-- language: lang-php -->
// get the contents
$s = file_get_contents( ... );
// does it need updating?
if( needs_update() )
{
$s = 'some new content';
file_put_contents( ... );
}
我可以看到发生的问题是,无论哪种情况导致“ needs_update()”返回true,都可能导致多个进程(几乎)同时更新同一文件。
在理想情况下,我将只有一个进程来更新文件,并阻止所有其他进程读取文件,直到完成为止。
因此,一旦“ needs_update()”返回true,我就会阻止其他进程读取文件。
<!-- language: lang-php -->
// wait here if anybody is busy writing to the file.
wait_if_another_process_is_busy_with_the_file();
// get the contents
$s = file_get_contents( ... );
// does it need updating?
if( needs_update() )
{
// prevent read/write access to the file for a moment
prevent_read_write_to_file_and_wait();
// rebuild the new content
$s = 'some new content';
file_put_contents( ... );
}
这样,只有一个进程可能会更新文件,并且文件都将获取最新值。
关于如何预防此类冲突有什么建议吗?
谢谢
FFMG
您正在寻找羊群功能。只要每个访问该文件的人都可以使用flock。来自php手册的示例:
$fp = fopen("/tmp/lock.txt", "r+");
if (flock($fp, LOCK_EX)) { // acquire an exclusive lock
ftruncate($fp, 0); // truncate file
fwrite($fp, "Write something here\n");
fflush($fp); // flush output before releasing the lock
flock($fp, LOCK_UN); // release the lock
} else {
echo "Couldn't get the lock!";
}
fclose($fp);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句