PHP solves the problem of multiple processes reading and writing a file at the same time

What should I say about this problem? First of all, PHP does not support multi-threading, so I think you should be talking about multi-process. For file operations, in fact, you only need to lock the file to solve it, no other operations are required. PHP's flock has done it for you.

/**
*flock(file,lock,block)
*file 必需,规定要锁定或释放的已打开的文件
*lock 必需。规定要使用哪种锁定类型。
*block 可选。若设置为 1 或 true,则当进行锁定时阻挡其他进程。
*lock
*LOCK_SH 要取得共享锁定(读取的程序)
*LOCK_EX 要取得独占锁定(写入的程序)
*LOCK_UN 要释放锁定(无论共享或独占)
*LOCK_NB 如果不希望 flock() 在锁定时堵塞
*/


$file = fopen("test.txt","w+");    // 打开文件
 
// 排它性的锁定 先锁上,写完,解锁。

if (flock($file,LOCK_EX)){

    fwrite($file,"Write something");

    flock($file,LOCK_UN);    // 文件解锁

}else{

  echo "Error locking file!";

}

fclose($file);    // 关闭文件

Guess you like

Origin blog.csdn.net/weixin_43452467/article/details/113251221