Jump to content

concurrent write file


voodoochicken

Recommended Posts

Hi, i am trying to do some stuff where if a web user runs a script that outputs a file, if the file does not exist, this user creates the file for all users, but if the file already exists, then the user can read the file somebody else created before (a cache). the file name does not have anything to do with the user id or user name, since is the same file for all users (but is created for everyone by the first user that requests it). what worries me is, what happens if many users try to create the file at the same time? say for example, somebody runs a statement 'fopen' with 'w' mode, but other user makes the same request, on the same file, before the previous user has closed the file, so more than one user is trying to open the file as 'w' at the same time, what happens there? does the 'w' mode puts a lock in the file for other threads? what goes there?tnx

Link to comment
Share on other sites

i think you going to need http://php.net/function.flock
hi, tnx! this seems to be what works there. according to the description, i would need to do something like$retries=0;$success=false;do{ if (file_already_exists() ){ $success=true; include("file.php"); } else { // try to generate file for everybody $file= fopen("file.php", "w"); if ($file) $continue= flock(file, LOCK_EX); if ($continue) $continue=generate_file(); if ($continue) fclose($file); if ($continue) $continue=flock(file, LOCK_UN); if ($continue) { $success=true; $include("file.php"); } else // maybe with a little more time the other thread can finish the file wait_5_seconds(); } $retries+=1;} while ($retries<$max_retries && !$success);this is what i have in mind (more or less), any pointers? tnx
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...