swoole / swoole-src

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

cancel coroutine ! #5373

Closed Tak-Pesar closed 5 months ago

Tak-Pesar commented 5 months ago

Hi, I want to terminate a created coroutine and finish the process but it is not possible by canceling it. And it just rejects things like sleep asynchronous , how can i make it stop fully and kill it process without use pcntl or another things... ?!

Swoole\Coroutine\run(function() : void {
    $cid = Swoole\Coroutine::create(function() : void {
        while(true){
            Swoole\Coroutine::sleep(2);
            echo 'Hello Swoole';
        }
    });
    Swoole\Coroutine::cancel($cid);
});
NathanFreeman commented 5 months ago

The "Swoole\Coroutine::cancel($cid)" only cancels the current sleep operation and returns false. So the condition of your while loop still remains true, which means the coroutine will keep running.

Tak-Pesar commented 5 months ago

So how can I completely eliminate and stop it ? This loop is just an example and I cannot change it

matyhtf commented 5 months ago

@Tak-Pesar It is impossible to directly kill a coroutine. Usually, it is necessary to check the return value of a channel or other io operation. If the return value is false and Co::isCanceled() returns True, it means that another coroutine is canceling this coroutine. In this case, you should actively exit the current coroutine.

Tak-Pesar commented 5 months ago

@matyhtf , Sorry, but as I said, I don't have control over the created Coroutine and I can't change it code , do you think use pcntl is a good way ? i mean , make child process and run every Coroutine in that and i can kill it later fully !

Tak-Pesar commented 5 months ago

I don't want to make child process and kill it later ! so , there isn't another way ?! I really need it ... @matyhtf , @NathanFreeman

twose commented 4 months ago

@Tak-Pesar If you really needs the feature, how about trying this? https://github.com/swow/swow/blob/develop/examples/coroutine/interrupt.php

matyhtf commented 4 months ago

@Tak-Pesar
There isn't an elegant way to gracefully terminate a single thread or coroutine within a process, as they are merely workflows within program execution.

Typically, you would need to terminate the entire process, which can be achieved by using functions like shell_exec or proc_open to spawn a separate process for running some code. If you're not concerned about it completing, you can forcefully terminate it with kill -9.