Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

multithreading - PHP file write threading issues

In a PHP webpage, Im opening a file in write mode, reading and than deleting the first line and closing the file. (The file has 1000's of lines)

Now, what the problem is, if there are like 100 users connected to that page, all will be opening that file in write mode and than try to write it after deleting the first line. Will there be any deadlocks in this situation?

For your information, we are using Windows server with IIS server and PHP5.
Thanks in advance for your help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use flock to grant access to file only for one user at a time.

But don't forget release your file lock by fclose

Update. Consider this code:

<?php
$start = time();
echo 'Started at '.$start.'<br />';
$filename = 'D:KindleooksBrenson_Teryaya_nevinnost__Avtobiografiya_66542.mobi';
$fp = fopen($filename, 'w+') or die('have no access to '.$filename);

if (flock($fp, LOCK_EX)) {
    echo 'File was locked at '.time().'. Granted exclusive access to write<br />';
}
else {
    echo 'File is locked by other user<br />';
}
sleep(3);
flock($fp, LOCK_UN);
echo 'File lock was released at '.time().'<br />';
fclose($fp);
$end = time();
echo 'Finished at '.$end.'<br />';
echo 'Proccessing time '.($end - $start).'<br />';

Run this code twice (it locks file for 3 seconds, so let's consider our manual script run as asynchronous). You will see something like this:

First instance:

  • File was locked at 1302788738. Granted exclusive access to write
  • File lock was released at 1302788741

Second:

  • File was locked at 1302788741. Granted exclusive access to write
  • File lock was released at 1302788744

Notice, that second instance waited for first to release file lock.

If it does not comply your requirements, well... try to invent other solution like: user can read file, then he edit one line and save it as temporary, other user saves his temporary file and so on and once you have all users released file lock, you compose new file as patch of all temporary files on each other (use save files mtime to define which file should stratify other one)... Something like this.... maybe... I'm not the expert in this kind of tasks, unfortunately - just my assumption on how you can get this done.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...