Example of PHP file lock-based multi-process reading/writing a file at the same time,
This example describes how PHP solves the problem of multiple processes simultaneously reading and writing a file based on the file lock. We will share this with you for your reference. The details are as follows:
First, PHP supports processes rather than multithreading (this should be clarified first). For file operations, you only need to lock the files and do not need other operations, PHP flock has already been done for you.
Use flock to lock a file before writing it, and unlock it after writing it. This enables multiple threads to read and write a file at the same time to avoid conflicts. This is probably the process below.
/** Flock (file, lock, block) * file is required. It specifies that * lock is required for an opened file to be locked or released. Specifies the type of lock to be used. * Optional. If it is set to 1 or true, other processes are blocked when the lock is performed. * Lock * LOCK_SH to obtain the shared lock (read program) * LOCK_EX to obtain the exclusive lock (written Program) * LOCK_UN to release the lock (whether shared or exclusive) * LOCK_NB if you do not want flock () to be blocked at lock time/* if (flock ($ file, LOCK_EX) {fwrite ($ file, 'Write more word '); flock ($ file, LOCK_UN);} else {// handle error logic} fclose ($ file );)