Functions.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. function wait(Closure $closure, ?float $timeout = null)
  29. {
  30. if (ApplicationContext::hasContainer()) {
  31. $waiter = ApplicationContext::getContainer()->get(Waiter::class);
  32. return $waiter->wait($closure, $timeout);
  33. }
  34. return (new Waiter())->wait($closure, $timeout);
  35. }
  36. function co(callable $callable): bool|int
  37. {
  38. $id = Coroutine::create($callable);
  39. return $id > 0 ? $id : false;
  40. }
  41. function defer(callable $callable): void
  42. {
  43. Coroutine::defer($callable);
  44. }
  45. function go(callable $callable): bool|int
  46. {
  47. $id = Coroutine::create($callable);
  48. return $id > 0 ? $id : false;
  49. }
  50. /**
  51. * Run callable in non-coroutine environment, all hook functions by Swoole only available in the callable.
  52. *
  53. * @param array|callable $callbacks
  54. */
  55. function run($callbacks, int $flags = SWOOLE_HOOK_ALL): bool
  56. {
  57. if (Coroutine::inCoroutine()) {
  58. throw new RuntimeException('Function \'run\' only execute in non-coroutine environment.');
  59. }
  60. Runtime::enableCoroutine($flags);
  61. /* @phpstan-ignore-next-line */
  62. $result = \Swoole\Coroutine\run(...(array) $callbacks);
  63. Runtime::enableCoroutine(false);
  64. return $result;
  65. }