Skip to content

Instantly share code, notes, and snippets.

@crusj
Created August 27, 2019 01:45
Show Gist options
  • Save crusj/893003a66dc4c927043c7fd83981e152 to your computer and use it in GitHub Desktop.
Save crusj/893003a66dc4c927043c7fd83981e152 to your computer and use it in GitHub Desktop.
PHP文件锁,防止争抢
<?php
/**
* author jianglong
* date 2019/8/5 下午5:00
*/
/**
* 文件锁
* Trait FileLock
* @author jianglong
*/
trait FileLock
{
public static function callWithLock($class, $method, $param, $lockFileName)
{
if (!is_dir('../runtime/lock')) {
mkdir('../runtime/lock', 0777, true);
}
$resource = fopen('../runtime/lock/' . $lockFileName, 'w+');
if (flock($resource, LOCK_EX)) {//排它锁
$rsl = call_user_func_array([$class, $method], $param);
flock($resource, LOCK_UN);//解锁
}
fclose($resource);
return $rsl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment