swoole / swoole-src

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

swoole4.5.9版本在defer()里执行$wg->done()时,不能全部执行成功 #5086

Closed afdafd closed 1 year ago

afdafd commented 1 year ago

Please answer these questions before submitting your issue.

  1. What did you do? If possible, provide a simple script for reproducing the error. 这是示例代码
    
    $wg = new WaitGroup();
    foreach (range(1,2) as $i) {
        vdump("add $i");
       $wg->add();
       sgo(function () use($wg, $i) {   
           vdump("start $i");
           defer(function () use($wg, $i) {
               vdump("defer $i");
               $wg->done();
              vdump("done $i");
          });
          vdump("end $i");
    });
    }

vdump("wait"); $wg->wait(); vdump("finish");`



2. What did you expect to see?
我希望的结果是:defer函数里的done()都能正常执行

3. What did you see instead?
现实结果是:只有一个done()成功执行了,第二个done()没有执行成功,然后就一直阻塞在那里了,一下执行结果输出:
![image](https://github.com/swoole/swoole-src/assets/26407222/88c38c24-d12b-40e1-a60e-7caa0f413c06)

4. What version of Swoole are you using (show your `php --ri swoole`)?
这是我的swoole版本
![image](https://github.com/swoole/swoole-src/assets/26407222/bcbf7d85-9705-41c9-a56c-d7b18fde1647)

6. What is your machine environment used (show your `uname -a` & `php -v` & `gcc -v`) ?

#### 电脑mac:
Darwin fengzideMacBook-Pro.local 22.5.0 Darwin Kernel Version 22.5.0: Mon Apr 24 20:52:24 PDT 2023; root:xnu-8796.121.2~5/RELEASE_ARM64_T6000 arm64

#### php版本
PHP 7.3.33 (cli) (built: Jun 17 2023 06:28:54) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.33, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.3.33, Copyright (c) 1999-2018, by Zend Technologies
    with Sdebug v2.9.3-dev, Copyright (c) 2002-2020, by Derick Rethans

7 说明:
1 . 这个sgo()是swoft框架里封装一个全局函数,里面实际执行的 Coroutine::create()方法。swoft框架自己也实现了一个waitGroup类,然后在sgo()函数用到了。可能是框架里的waitGroup影响到了,但是我把swoole升级到4.6.7后,上面的代码执行就正常了,没有出现任何问题了
NathanFreeman commented 1 year ago

4.5.9这个版本不维护了,可以升级到最新的4.8或者5.0.3

matyhtf commented 1 year ago

最新版本测试没有问题,无法重现。

代码


<?php
Co\run(function (){
    $wg = new Swoole\Coroutine\WaitGroup();
    foreach (range(1,2) as $i) {
        var_dump("add $i");
        $wg->add();
        Co\go(function () use($wg, $i) {
            var_dump("start $i");
            defer(function () use($wg, $i) {
                var_dump("defer $i");
                $wg->done();
                var_dump("done $i");
            });
            var_dump("end $i");
        });
    }

    var_dump("wait");
    $wg->wait();
    var_dump("finish");
});

输出

$ php wg.php 
string(5) "add 1"
string(7) "start 1"
string(5) "end 1"
string(7) "defer 1"
string(6) "done 1"
string(5) "add 2"
string(7) "start 2"
string(5) "end 2"
string(7) "defer 2"
string(6) "done 2"
string(4) "wait"
string(6) "finish"