Lock.php 999 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. namespace easyTask;
  3. use \Closure as Closure;
  4. /**
  5. * Class Lock
  6. * @package easyTask
  7. */
  8. class Lock
  9. {
  10. /**
  11. * 锁文件
  12. * @var string
  13. */
  14. private $file;
  15. /**
  16. * 构造函数
  17. * @param string $name
  18. */
  19. public function __construct($name = 'lock')
  20. {
  21. //初始化文件
  22. $path = Helper::getLokPath();
  23. $this->file = $path . md5($name);
  24. if (!file_exists($this->file))
  25. {
  26. @file_put_contents($this->file, '');
  27. }
  28. }
  29. /**
  30. * 加锁执行
  31. * @param Closure $func
  32. * @param bool $block
  33. * @return mixed
  34. */
  35. public function execute($func, $block = true)
  36. {
  37. $fp = fopen($this->file, 'r');
  38. $is_flock = $block ? flock($fp, LOCK_EX) : flock($fp, LOCK_EX | LOCK_NB);
  39. $call_back = null;
  40. if ($is_flock)
  41. {
  42. $call_back = $func();
  43. flock($fp, LOCK_UN);
  44. }
  45. fclose($fp);
  46. return $call_back;
  47. }
  48. }