Join 4,000+ others and never miss out on new tips, tutorials, and more.
Latest version:
pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5
<?php OpenSwoole\Coroutine::cancel(int $cid): bool
Coroutine ID, the coroutine ID you want to cancel/terminate. You cannot cancel the current coroutine.
Returns true
if the coroutine was successfully cancelled and false
if there was a problem, use OpenSwoole\Util::getLastErrorCode()
to see what went wrong.
Cancel the execution (terminate) of a coroutine based on a coroutine ID. You can get the ID of a coroutine with Coroutine::getCid()
, this allows you to then cancel that coroutine but you can't cancel (terminate) the current coroutine you are in.
Coroutine cancel error codes (get with OpenSwoole\Util::getLastErrorCode()
):
OpenSwoole\Constant::ERROR_CO_CANNOT_CANCEL
OpenSwoole\Constant::ERROR_CO_NOT_EXISTS
OpenSwoole\Constant::ERROR_CO_CANCELED
You can use OpenSwoole\Coroutine::isCanceled()
to check if a coroutine has been cancelled.
Since v4.7.0
You should not cancel the current coroutine or non-existing coroutines.
<?php
use OpenSwoole\Coroutine;
co::run(function()
{
assert(Coroutine::cancel(Coroutine::getCid()) === false);
assert(OpenSwoole\Util::getLastErrorCode() === OpenSwoole\Constant::ERROR_CO_CANNOT_CANCEL);
assert(Coroutine::cancel(999) === false);
assert(OpenSwoole\Util::getLastErrorCode() === OpenSwoole\Constant::ERROR_CO_NOT_EXISTS);
});
<?php
use OpenSwoole\Coroutine;
use OpenSwoole\Coroutine\System;
co::run(function()
{
$cid = Coroutine::getCid();
go(function() use ($cid)
{
System::usleep(2000);
assert(Coroutine::cancel($cid) === true);
});
$retval = Coroutine::yield();
echo "Done\n";
assert($retval === false);
assert(OpenSwoole\Util::getLastErrorCode() === OpenSwoole\Constant::ERROR_CO_CANCELED);
});
<?php
use OpenSwoole\Coroutine;
use OpenSwoole\Event;
use OpenSwoole\Coroutine\System;
use function OpenSwoole\co::run;
co::run(function()
{
$cid = Coroutine::getCid();
Event::defer(function() use ($cid)
{
assert(Coroutine::cancel($cid) === true);
});
$retval = System::gethostbyname('openswoole.com');
echo "Done\n";
assert($retval === false);
assert(OpenSwoole\Util::getLastErrorCode() === OpenSwoole\Constant::ERROR_AIO_CANCELED);
});