Swoole-src: How to use blocking coroutines before Swoole\Server::start() ?

Created on 4 Dec 2020  ·  2Comments  ·  Source: swoole/swoole-src

Question

  • How can coroutines be used before the HTTP server starts? without the error Swoole\Server::start(): eventLoop has already been created, unable to start Swoole\Http\Server

Example:

# Blocking function to pre-load/refresh some cache in static variables (faster than the table/have the ram).
function cacheData() {
  $wg = new Swoole\Coroutine\WaitGroup();
  # async  IO
  go(function () use ($wg) { $wg->add(1); IO::code(); $wg->done(); });
  go(function () use ($wg) { $wg->add(1); IO::code(); $wg->done(); });
  go(function () use ($wg) { $wg->add(1); IO::code(); $wg->done(); });
  go(function () use ($wg) { $wg->add(1); IO::code(); $wg->done(); });
  # wait for all of them
  $wg->wait();
}

...
cacheData(); # Load the data before the server start

$http = new Server($listen_ip, $listen_port);
# Refresh the data inside each worker at a set interval.
$http->on('workerStart', function(Server $server, int $worker_id) {
   Timer::tick(1000, function () { cacheData(); });  
});
...
$http->start(); # << error: Swoole\Server::start(): eventLoop has already been created, unable to start Swoole\Http\Server

Most helpful comment

Awesome, thank you, makes sense now.

The Chinese documentation (wiki.swoole.com) seems very good and logical, but once passed through google translate, it can lose some info/semantics, so some terms become confusing/not so clear.

All 2 comments

You need to use theSwoole\Coroutine\run method and then use the coroutine inside:

<?php

use Swoole\Http\Server;

use function Swoole\Coroutine\run;

run(function () {
        $wg = new Swoole\Coroutine\WaitGroup();
  # async  IO
  go(function () use ($wg) { $wg->add(1); IO::code(); $wg->done(); });
  go(function () use ($wg) { $wg->add(1); IO::code(); $wg->done(); });
  go(function () use ($wg) { $wg->add(1); IO::code(); $wg->done(); });
  go(function () use ($wg) { $wg->add(1); IO::code(); $wg->done(); });
  # wait for all of them
  $wg->wait();
});

$http = new Server("0.0.0.0", 49501);

$http->on('request', function ($request, $response) {
    $response->end("<h1>Hello World. #".rand(1000, 9999)."</h1>");
});
$http->start();

Awesome, thank you, makes sense now.

The Chinese documentation (wiki.swoole.com) seems very good and logical, but once passed through google translate, it can lose some info/semantics, so some terms become confusing/not so clear.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sagesan picture sagesan  ·  4Comments

sshymko picture sshymko  ·  3Comments

daslicht picture daslicht  ·  4Comments

jerryli1 picture jerryli1  ·  4Comments

rovico picture rovico  ·  4Comments