Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the conflict between reading and writing files concurrently in php

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "how to solve the problem of conflict between reading and writing files in php". In daily operation, I believe that many people have doubts about how to solve the problem of conflict between reading and writing files in php. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to solve the problem of "how to solve the conflict between reading and writing files concurrently in php". Next, please follow the editor to study!

The general solution would be:

The copy code is as follows:

$fp=fopen ('/ tmp/lock.txt','w+')

If (flock ($fp,LOCK_EX)) {

Fwrite ($fp, "Write something here\ n")

Flock ($fp,LOCK_UN)

} else {

Echo 'Couldn\' t lock the file!'

}

Fclose ($fp)

But in PHP, flock doesn't seem to work so well! In the case of multiple concurrency, it seems that resources are often monopolized, not released immediately, or not released at all, resulting in a deadlock, resulting in a high cpu occupation of the server, and sometimes even let the server die completely. It seems that this happens in many linux/unix systems. So be sure to think carefully before using flock.

So there is no solution? In fact, this is not the case. If we use flock () properly, it is entirely possible to solve the deadlock problem. Of course, if you do not consider using the flock () function, there will also be a good solution to our problem. After my personal collection and summary, I roughly summed up the following solutions.

Scheme 1: when locking the file, set a timeout. The approximate implementation is as follows:

The copy code is as follows:

If ($fp=fopen ($fileName,'a')) {

$startTime=microtime ()

Do {

$canWrite=flock ($fp,LOCK_EX)

If (! $canWrite) {

Usleep (round (rand (0100) * 1000))

}

} while (! $canWrite) & & ((microtime ()-$startTime))

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report