swoole / swoole-src

🚀 Coroutine-based concurrency library for PHP
https://www.swoole.com
Apache License 2.0
18.44k stars 3.16k forks source link

How to use blocking coroutines before Swoole\Server::start() ? #3912

Closed ValiDrv closed 3 years ago

ValiDrv commented 3 years ago

Question

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
huanghantao commented 3 years ago

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();
ValiDrv commented 3 years ago

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.