This article is mainly to share with you the PHP file lock concurrency operation, the default: PHP file operation function, not blocking state, but free operation State, hope to help everyone.
Conditions:
Lock Operation Flow:
Lock type:
Read Lock: S-lock (share-lock) shared lock, expected to increase lock before read operation. Causes, allows concurrent reads, and blocks additional writes.
Write Lock: X-lock (Exclusive-lock) exclusive lock, exclusive lock, write operation before attempting to add a lock type. Cause, other scripts cannot be read or written.
Intent Lock: All scripts that manipulate resources follow a convention to use file locks (conventions).
Blocking: Refers to the next action on a file lock to continue after the previous operation has been unlocked
Function:
BOOL Flock (resource $handle, int $operation [, int & $wouldblock])
Type parameter ( $operation
): LOCK_SH
read lock and LOCK_EX
write lock
Cases:
Use read lock:
Using Write Locks:
The LOCK_NB can be used to not block when the lock fails:
<?PHP$FP = fopen ('/tmp/lock.txt ', ' r+ ');/* Activate the LOCK_NB option on an LOCK_EX operation */if (!flock ($fp, LOCK_EX | LOCK_NB) { echo ' unable to obtain lock '; Exit (-1);} /* */fclose ($FP);
Unlock: Locks are also released by Fclose (automatically called after the script ends) before PHP 5.3.2, and can now be unlocked flock($fp,LOCK_UN)
manually
Default: PHP file operation function, not blocking state, but free operation state.
Conditions:
Lock Operation Flow:
Lock type:
Read Lock: S-lock (share-lock) shared lock, expected to increase lock before read operation. Causes, allows concurrent reads, and blocks additional writes.
Write Lock: X-lock (Exclusive-lock) exclusive lock, exclusive lock, write operation before attempting to add a lock type. Cause, other scripts cannot be read or written.
Intent Lock: All scripts that manipulate resources follow a convention to use file locks (conventions).
Blocking: Refers to the next action on a file lock to continue after the previous operation has been unlocked
Function:
BOOL Flock (resource $handle, int $operation [, int & $wouldblock])
Type parameter ( $operation
): LOCK_SH
read lock and LOCK_EX
write lock
Cases:
Use read lock:
Using Write Locks:
The LOCK_NB can be used to not block when the lock fails:
<?PHP$FP = fopen ('/tmp/lock.txt ', ' r+ ');/* Activate the LOCK_NB option on an LOCK_EX operation */if (!flock ($fp, LOCK_EX | LOCK_NB) { echo ' unable to obtain lock '; Exit (-1);} /* */fclose ($FP);
Unlocked: Before PHP 5.3.2, locks are also released by Fclose (automatically called after the end of the script) and can now be unlocked manually via the flock ($fp, Lock_un)
.