AtomicManager.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Memory;
  12. use RuntimeException;
  13. use Swoole\Atomic;
  14. class AtomicManager
  15. {
  16. /**
  17. * A container that use to store atomic.
  18. */
  19. private static array $container = [];
  20. /**
  21. * You should initialize an Atomic with the identifier before use it.
  22. */
  23. public static function initialize(string $identifier, int $value = 0): void
  24. {
  25. static::$container[$identifier] = new Atomic($value);
  26. }
  27. /**
  28. * Get an initialized Atomic from container by the identifier.
  29. *
  30. * @throws RuntimeException when the Atomic with the identifier has not initialization
  31. */
  32. public static function get(string $identifier): Atomic
  33. {
  34. if (! isset(static::$container[$identifier])) {
  35. throw new RuntimeException('The Atomic has not initialization yet.');
  36. }
  37. return static::$container[$identifier];
  38. }
  39. /**
  40. * Remove the Atomic by the identifier from container after used,
  41. * otherwise will occur memory leaks.
  42. */
  43. public static function clear(string $identifier): void
  44. {
  45. unset(static::$container[$identifier]);
  46. }
  47. }