php基于协程实现异步的方法分析
作者:llj1985 发布时间:2023-06-11 10:08:39
标签:php,协程,异步
本文实例讲述了php基于协程实现异步的方法。分享给大家供大家参考,具体如下:
github上php的协程大部分是根据这篇文章实现的:http://nikic.github.io/2012/12/22/Cooperative-multitasking-using-coroutines-in-PHP.html。
它们最终的结果都是把回调变成了优雅的顺序执行的代码,但还是阻塞的,不是真正的异步。
比如最热门的:https://github.com/recoilphp/recoil
先安装:
composer require recoil/recoil
执行:
<?php
//recoil.php
include __DIR__ . '/vendor/autoload.php';
use Recoil\React\ReactKernel;
$i = 100000;
ReactKernel::start(task1());
ReactKernel::start(task2());
function task1(){
global $i;
echo "wait start" . PHP_EOL;
while ($i-- > 0) {
yield;
}
echo "wait end" . PHP_EOL;
};
function task2(){
echo "Hello " . PHP_EOL;
yield;
echo "world!" . PHP_EOL;
}
结果:
wait start
//等待若干秒
wait end
Hello
world!
我本来是想让两个任务并行,结果两个任务变成了串行,中间等待的时间什么事情都干不了。React响应式的编程是严格禁止这种等待的,所以我就参照unity3d的协程自己写了个php版本的。上代码:
<?php
//Coroutine.php
//依赖swoole实现的定时器,也可以用其它方法实现定时器
class Coroutine
{
//可以根据需要更改定时器间隔,单位ms
const TICK_INTERVAL = 1;
private $routineList;
private $tickId = -1;
public function __construct()
{
$this->routineList = [];
}
public function start(Generator $routine)
{
$task = new Task($routine);
$this->routineList[] = $task;
$this->startTick();
}
public function stop(Generator $routine)
{
foreach ($this->routineList as $k => $task) {
if($task->getRoutine() == $routine){
unset($this->routineList[$k]);
}
}
}
private function startTick()
{
swoole_timer_tick(self::TICK_INTERVAL, function($timerId){
$this->tickId = $timerId;
$this->run();
});
}
private function stopTick()
{
if($this->tickId >= 0) {
swoole_timer_clear($this->tickId);
}
}
private function run()
{
if(empty($this->routineList)){
$this->stopTick();
return;
}
foreach ($this->routineList as $k => $task) {
$task->run();
if($task->isFinished()){
unset($this->routineList[$k]);
}
}
}
}
class Task
{
protected $stack;
protected $routine;
public function __construct(Generator $routine)
{
$this->routine = $routine;
$this->stack = new SplStack();
}
/**
* [run 协程调度]
* @return [type] [description]
*/
public function run()
{
$routine = &$this->routine;
try {
if(!$routine){
return;
}
$value = $routine->current();
//嵌套的协程
if ($value instanceof Generator) {
$this->stack->push($routine);
$routine = $value;
return;
}
//嵌套的协程返回
if(!$routine->valid() && !$this->stack->isEmpty()) {
$routine = $this->stack->pop();
}
$routine->next();
} catch (Exception $e) {
if ($this->stack->isEmpty()) {
/*
throw the exception
*/
return;
}
}
}
/**
* [isFinished 判断该task是否完成]
* @return boolean [description]
*/
public function isFinished()
{
return $this->stack->isEmpty() && !$this->routine->valid();
}
public function getRoutine()
{
return $this->routine;
}
}
测试代码:
<?php
//test.php
require 'Coroutine.php';
$i = 10000;
$c = new Coroutine();
$c->start(task1());
$c->start(task2());
function task1(){
global $i;
echo "wait start" . PHP_EOL;
while ($i-- > 0) {
yield;
}
echo "wait end" . PHP_EOL;
};
function task2(){
echo "Hello " . PHP_EOL;
yield;
echo "world!" . PHP_EOL;
}
结果:
wait start
Hello
world!
//等待几秒,但不阻塞
wait end
希望本文所述对大家PHP程序设计有所帮助。
来源:https://blog.csdn.net/llj1985/article/details/51684210


猜你喜欢
- 介绍海象运算符,即 := ,在 PEP 572 中被提出,并在 Python3.8 版本中发布。海象运算符的英文原名叫Assignment
- 观察者模式首先,提到观察者模式,这不禁让我想到了MVVM,MVVM架构模式感觉用到了观察者的思想。我们还是按照惯例,了解一下什么是观察者模式
- 描述给ChatGPT的描述内容:python在桌面上显示动态的文字,不要显示窗口边框。窗口背景和标签背景都是透明的,但标签内的文字是有颜色。
- 以一种有意义的方式组织数据可能是一项挑战。有时你需要的可能是一个简单的排序,但是通常你需要做更多,你需要分组来进行分析和统计。幸运的是,SQ
- 1. python-firepython-fire 是一个三方库,可以将任何 Python 对象变成一个命令行接口。使用前先 pip ins
- 在Python自带的编辑器IDLE中或者Python shell中不能使用cd命令,那么跳到目标路径呢。方法是使用os包下的相关函数实现路径
- 今天,在在使用 pycharm 的使用,进行创建 python的时候,发现使用默认的创建的选项使用的python 3环境 。而我系统默认的p
- common中存放的是整个项目中公共使用的封装方法从工程目录上可以看到区分datas中专门存放测试数据(yml文件)cases中专门集中存放
- Guide to the Section 508 Standards for Electronic and Information Tech
- SELECT * from table where username like '%陈哈哈%' and hobby like
- 继承是面向对象编程的一个重要的方式,因为通过继承,子类就可以扩展父类的功能。回忆一下Animal类层次的设计,假设我们要实现以下4种动物:&
- 1、su – oracle 不是必需,适合于没有DBA密码时使用,可以不用密码来进入sqlplus界面。 2、sqlplus /
- 1 索引基础1.1 索引作用在MySQL中,查找数据时先在索引中找到对应的值,然后根据匹配的索引记录找到对应的数据行,假如要运行下面查询语句
- 除了使用xlrd库或者xlwt库进行对excel表格的操作读与写,而且pandas库同样支持excel的操作;且pandas操作更加简介方便
- 概念softmax函数是常用的输出层函数,常用来解决互斥标签的多分类问题。当然由于他是非线性函数,也可以作为隐藏层函数使用反向传播求导可以看
- 一、相同点dump 和 dumps 都实现了序列化load 和 loads 都实现反序列化变量从内存中变成可存储或传输的过程称之为序列化序列
- 本文实例讲述了Python实现获取邮箱内容并解析的方法。分享给大家供大家参考,具体如下:# -*- coding: utf-8 -*-fro
- session_unset() 释放当前在内存中已经创建的所有$_SESSION变量,但不删除session文件以及不释放对应的sessio
- 一,uptime 可以查看系统的运行时间show global status like 'uptime';二,利用linux
- python远程控制电脑的具体代码,供大家参考,具体内容如下python拥有大量的第三方库,且语法简单。今天老杨就用python实现远程控制