Concurrent file access

Using:

fopen fwrite fclose 

What happens if two users try to open the same file at the same time?

+7
php
source share
5 answers

Small-scale file operations are so fast that two records at the same time are quite rare. Despite this, you can use flock to lock the file:

 $fp = fopen('file.log', 'a+'); flock($fp, LOCK_EX); fwrite($fp, 'my data'); flock($fp, LOCK_UN); fclose($fp); 

Note fclose automatically unlocks the file, but I find the code makes it more convenient to use.

+6
source share

Important:

  • What happens when they write
  • What happens if (a) reads, (b) reads then (b) writes then (a) writes? Is (a) wrong because the calculation is no longer inferred from the last state?

A classic example is the Cash machine / bank balance example used in many texts.

For any type of record sharing , some form of concurrent access control , such as mutex , is required, but there are many potential problems, such as race conditions , starvation, and variations on the philosopher canteen problem .

However, many operating systems allow file locking , which means that another process is waiting for the lock to be released. See PHP flock () for file locking.

You can also use the "checkout, change, commit / merge" approach.

Depending on your reasons, you might want to consider a database such as MySQL or SQLite , as they will provide faster, more reliable ways to share state with read-strength or without cache.

The many challenges, pitfalls and ways to share the state are enormous. Sorry for using Wikipedia.

+3
source share

Use file_put_contents() instead of the FILE_APPEND or LOCK_EX .

Any of these flags locks the file for writing.

+3
source share

Yes, you can open two files at the same time if you do not lock the [flock] file. However, the best time for a flock of files would be when you write to it, or if you decide to allow only one user to view the file anywhere.

+1
source share

It happens all the time. However, the answer to your question depends on what they want and want to do with the open file. Possible actions / decisions will solely depend on this requirement.

+1
source share

All Articles