Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Barrier类修改 #67

Closed
guiqibusixin opened this issue Oct 29, 2020 · 4 comments · Fixed by #68
Closed

Barrier类修改 #67

guiqibusixin opened this issue Oct 29, 2020 · 4 comments · Fixed by #68

Comments

@guiqibusixin
Copy link

guiqibusixin commented Oct 29, 2020

以下情况下不会抛出协程错误异常,正常执行

  • 执行的任务中没有发生协程切换
  • 执行任务列表为空,没有任务

修改后的类

use Swoole\Coroutine;
use Swoole\Exception;
use Swoole\Timer;

class Barrier
{
    private $cid = -1;

    private $timer = -1;

    private static $cancel_list = [];

    public function __destruct()
    {
        if ($this->timer != -1) {
            Timer::clear($this->timer);
            if (static::$cancel_list[$this->cid]) {
                unset(static::$cancel_list[$this->cid]);
                return;
            }
        }

        if ($this->cid != -1 && $this->cid != Coroutine::getCid()) {
            Coroutine::resume($this->cid);
        }else{
            self::$cancel_list[$this->cid] = true;
        }
    }

    public static function make()
    {
        return new static();
    }

    /**
     * @throws Exception
     */
    public static function wait(Barrier &$barrier, float $timeout = -1)
    {
        if ($barrier->cid != -1) {
            throw new Exception('The barrier is waiting, cannot wait again.');
        }
        $cid = Coroutine::getCid();
        $barrier->cid = $cid;
        if ($timeout > 0 && ($timeout_ms = intval($timeout * 1000)) > 0) {
            $barrier->timer = Timer::after($timeout_ms, function () use ($cid) {
                self::$cancel_list[$cid] = true;
                Coroutine::resume($cid);
            });
        }
        $barrier = null;
        (!(self::$cancel_list[$cid] ?? false)) && Coroutine::yield();
    }
}
@guiqibusixin
Copy link
Author

@sy-records ok ok

@guiqibusixin
Copy link
Author

@sy-records
wait方法中可以加上unset数组self::$cancel_list[$cid]

  • 不知道后面会不会出现协程id相同的情况下,导致协程没有等待。
  • 节省内存冗余空间
if (!isset(self::$cancel_list[$cid])) {
     Coroutine::yield();
}else {
    unset(self::$cancel_list[$cid]);
}

@sy-records
Copy link
Member

嗯,这里是有点问题。。我在等review,结果合并了😂

@guiqibusixin
Copy link
Author

@sy-records
好的好的,哈哈

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants