Lock.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /**
  3. * This file is part of workerman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. namespace GatewayWorker\Lib;
  15. /**
  16. * 锁
  17. * 基于文件锁实现
  18. */
  19. class Lock
  20. {
  21. /**
  22. * handle
  23. * @var resource
  24. */
  25. private static $fileHandle = null;
  26. /**
  27. * 获取锁
  28. * @param bool block
  29. * @return bool
  30. */
  31. public static function get($block=true)
  32. {
  33. $operation = $block ? LOCK_EX : LOCK_EX | LOCK_NB;
  34. if(self::getHandle())
  35. {
  36. return flock(self::$fileHandle, $operation);
  37. }
  38. return false;
  39. }
  40. /**
  41. * 释放锁
  42. * @return true
  43. */
  44. public static function release()
  45. {
  46. if(self::getHandle())
  47. {
  48. return flock(self::$fileHandle, LOCK_UN);
  49. }
  50. return false;
  51. }
  52. /**
  53. * 获得文件句柄
  54. * @return resource
  55. */
  56. protected static function getHandle()
  57. {
  58. if(!self::$fileHandle)
  59. {
  60. self::$fileHandle = fopen(__FILE__, 'r+');
  61. }
  62. return self::$fileHandle;
  63. }
  64. }