swoole-src icon indicating copy to clipboard operation
swoole-src copied to clipboard

Confused with enableCoroutine() over enable_coroutine

Open ljfreelancer88 opened this issue 2 years ago • 4 comments

Hi Swoole Team, I'm confused with these enableCoroutine() and enable_coroutine. Like when to use enableCoroutine() over enable_coroutine? I'm trying to grasp the implementation of coroutine in Swoole Server but I always go this PHP Warning: Swoole\Coroutine\Scheduler::start(): eventLoop has already been created. unable to start Swoole\Coroutine\Scheduler in @swoole-src/library/core/Coroutine/functions.php on line 24 error every time I used Co\run but I haven't define or use this yet.

\Swoole\Runtime::enableCoroutine();

$http = new Server("127.0.0.1", 9501, SWOOLE_PROCESS);
$http->set([
    'enable_coroutine' => true,
    'max_coroutine' => 10000,
]);

This is not working on my end. It throws eventLoop has already been created error.

use Swoole\Coroutine as Co;

Co\run(function() {
    go(function() {
        // Save to the database
    });

    go(function() {
        // Send bulk email
    });
});

This is working.

use Swoole\Coroutine;

Coroutine::create(function() {
        // Save to the database
});
Coroutine::create(function() {
        // Send bulk email
});

ljfreelancer88 avatar Aug 20 '21 13:08 ljfreelancer88

I did not reproduce your problem with the code you provided. Your third code segment is also incomplete.

Runtime::enableCoroutine is used to enable some hooks for the coroutine, default is SWOOLE_HOOK_ALL, Or you can use the hook_flags parameter to set hooks.

When enable_coroutine is set to false on the server, the coroutine is no longer automatically created in the event callback function.

sy-records avatar Aug 21 '21 10:08 sy-records

Thank you but how can I use the Co\run() without getting this PHP Warning: Swoole\Coroutine\Scheduler::start(): eventLoop has already been created. unable to start Swoole\Coroutine\Scheduler in @swoole-src/library/core/Coroutine/functions.php on line 24

ljfreelancer88 avatar Aug 21 '21 17:08 ljfreelancer88

The code you provided really does not reproduce the problem.

The problem only occurs when you nest Co\run, so you can troubleshoot it yourself.

use function Swoole\Coroutine\run;

run(function() {
    run(function () {

    });
});

sy-records avatar Aug 22 '21 11:08 sy-records

Server has already included a scheduler implictly, so you need not to call Co\run() or create new sheduler in it.

twose avatar Nov 04 '21 05:11 twose