Functions.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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\Coroutine;
  12. use Closure;
  13. use Hyperf\Context\ApplicationContext;
  14. use RuntimeException;
  15. use Swoole\Runtime;
  16. /**
  17. * @param callable[] $callables
  18. * @param int $concurrent if $concurrent is equal to 0, that means unlimited
  19. */
  20. function parallel(array $callables, int $concurrent = 0): array
  21. {
  22. $parallel = new Parallel($concurrent);
  23. foreach ($callables as $key => $callable) {
  24. $parallel->add($callable, $key);
  25. }
  26. return $parallel->wait();
  27. }
  28. /**
  29. * @template TReturn
  30. *
  31. * @param Closure():TReturn $closure
  32. * @return TReturn
  33. */
  34. function wait(Closure $closure, ?float $timeout = null)
  35. {
  36. if (ApplicationContext::hasContainer()) {
  37. $waiter = ApplicationContext::getContainer()->get(Waiter::class);
  38. return $waiter->wait($closure, $timeout);
  39. }
  40. return (new Waiter())->wait($closure, $timeout);
  41. }
  42. function co(callable $callable): bool|int
  43. {
  44. $id = Coroutine::create($callable);
  45. return $id > 0 ? $id : false;
  46. }
  47. function defer(callable $callable): void
  48. {
  49. Coroutine::defer($callable);
  50. }
  51. function go(callable $callable): bool|int
  52. {
  53. $id = Coroutine::create($callable);
  54. return $id > 0 ? $id : false;
  55. }
  56. /**
  57. * Run callable in non-coroutine environment, all hook functions by Swoole only available in the callable.
  58. *
  59. * @param array|callable $callbacks
  60. */
  61. function run($callbacks, int $flags = SWOOLE_HOOK_ALL): bool
  62. {
  63. if (Coroutine::inCoroutine()) {
  64. throw new RuntimeException('Function \'run\' only execute in non-coroutine environment.');
  65. }
  66. Runtime::enableCoroutine($flags);
  67. /* @phpstan-ignore-next-line */
  68. $result = \Swoole\Coroutine\run(...(array) $callbacks);
  69. Runtime::enableCoroutine(0);
  70. return $result;
  71. }