This article is an example of the PHP file writing method to respond to multithreaded writing, the specific code is as follows:
function File_write ($file _name, $text, $mode = ' A ', $timeout =30) {
$handle = fopen ($file _name, $mode);
while ($timeout >0) {
if (flock ($handle, LOCK_EX)) {//Exclusive locking
$timeout-;
Sleep (1);
}
}
if ($timeout > 0) {
fwrite ($handle, $text. \ n ');
Flock ($handle, lock_un);
Fclose ($handle); Release lock operation return
true;
}
return false;
}
Where the flock (int $handle, int $operation) function operation handle must be a file pointer that is already open.
Operation can be one of the following values:
To obtain a shared lock (read program), set the operation to Lock_sh (PHP 4.0.1 Previous version is 1).
To obtain an exclusive lock (written program), set the operation to LOCK_EX (2 in the previous version of PHP 4.0.1).
To release the lock (either shared or exclusive), set the operation to Lock_un (3 in the previous version of PHP 4.0.1).
If you do not want flock () to be blocked when locked, add LOCK_NB to Operation (set to 4 in previous versions of PHP 4.0.1).
In addition, the fclose () is used to release the lock operation, which is invoked when the code finishes executing.