cj333
cj333

Reputation: 2609

php how to lock a file only for read when it is writing?

I have a page with a larger query form mysql, the results could be more than 2MB. Because I haven't got enough memory on my server (I should arrange the memory for mysql to speed up query time), I have given up memcached. instead it is a txt file.

How to lock a file like this situation? If the file is lock, only read, if file isn't lock, first write then read. thanks.

if((time()-filemtime(filename)) > 60){
   //mysql_query;  query time less than 1.5 seconds
   if(ex_lock){ // if file is lock, only read
      file_get_contents($filename);
   }else{  // if file isn't lock, first write then read
      file_put_contents($filename, $query_contents);//some file size could be 2mb
      file_get_contents($filename);
   }
}

Upvotes: 0

Views: 66

Answers (1)

nyson
nyson

Reputation: 1055

Use flock(), but if you're creating result sets with 2MB of data I'd suggest you cache them. Does the result set really need to be updated every other second?

Upvotes: 1

Related Questions