Skip to content

Enhance Coroutine::cancel() to throw an exception after canceling an IO operation #5828

@tw2066

Description

@tw2066

目前执行cancel只会中断当前io操作, 程序还是会往下执行

use \Swoole\Coroutine;

\Swoole\Coroutine::set(['hook_flags' => SWOOLE_HOOK_ALL]);
\Swoole\Coroutine\run(function () {
    $cid = Coroutine::create(function () {
        for($i = 0; $i < 5; $i++) {
            $bool = Coroutine::sleep(1.0);
            var_dump($bool);
            print_r('$bool:'.$bool . '  '.$i);
            echo PHP_EOL;

        }
    });
    sleep(3);


    $bool = Swoole\Coroutine::cancel($cid);
    var_dump('cancel:'.$bool);

    sleep(5);
});

希望
增加 第2个参数(isThrow ),是否触发报错

当传入true时, cancel遇到io时,底层触发报错
终止当前协程; 达到类似kill的功能

Swoole\Coroutine::cancel($cid,bool isThrow = false): bool

use \Swoole\Coroutine;

\Swoole\Coroutine::set(['hook_flags' => SWOOLE_HOOK_ALL]);
\Swoole\Coroutine\run(function () {
    $cid = Coroutine::create(function () {
        for($i = 0; $i < 5; $i++) {
            $bool = Coroutine::sleep(1.0);
            // swoole 底层支持
            if ($bool === false){
                throw new Exception('coroutine cancel');
            }
            var_dump($bool);
            print_r('$bool:'.$bool . '  '.$i);
            echo PHP_EOL;
        }
    });
    sleep(3);


    $bool = Swoole\Coroutine::cancel($cid);
    var_dump('cancel:'.$bool);

    sleep(5);
});

控制台

bool(true)
$bool:1  0
bool(true)
$bool:1  1
PHP Fatal error:  Uncaught Exception: coroutine cancel in /home/test.php:10
Stack trace:
#0 [internal function]: {closure}()
#1 {main}
  thrown in /home/test.php on line 10

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions