前言
第一部分: 半协程调度器
- 统一生成器接口
- 生成器迭代
- 生成器返回值
- 生成器委托
- 改写 return
- 抽象异步模型
- 引入异常处理
- 异常: 嵌套任务透传
- 异常: 传递流程
- 异常: 重新进行 CPS 变换
- 异常: 重新加入 Async
- Syscall 与 Context
- 调度器: 里程碑
- spawn
- callcc
- race 与 timeout
- all 与 parallel
- channel 与协程间通信
- 无缓存 channel
- 缓存 channel
- channel 演示
- FutureTask 与 fork
第二部分: Koa
- 穿越地心之旅
- 洋葱圈模型
- rightReduce与中间件compose
- Koa::Application
- Koa::Context
- Koa::Request
- Koa::Response
- Koa - HelloWorld
- Middleware Interface
- Middleware: 全局异常处理
- Middleware: Router
- Middleware: 请求超时
- 一个综合示例
附录
参考
文章来源于网络收集而来,版权归原创者所有,如有侵权请及时联系!
抽象异步模型
抽象异步模型
对回调模型抽象出异步接口Async
。
只有一个方法的接口通常都可以使用闭包代替,区别在于interface引入新类型,闭包则不会。如果说thunkify依赖了参数顺序的弱约定,Async相对严肃的依赖了类型。
<?php
interface Async
{
public function begin(callable $callback);
}
// AsyncTask符合Async定义, 实现Async
final class AsyncTask implements Async
{
public function next($result = null)
{
$value = $this->gen->send($result);
if ($this->gen->valid()) {
// \Generator -> Async
if ($value instanceof \Generator) {
$value = new self($value);
}
if ($value instanceof Async) {
$async = $value;
$continuation = [$this, "next"];
$async->begin($continuation);
} else {
$this->next($value);
}
} else {
$cc = $this->continuation;
$cc($result);
}
}
}
两个简单的对回调接口转换例子:
<?php
// 定时器修改为标准异步接口
class AsyncSleep implements Async
{
public function begin(callable $cc)
{
swoole_timer_after(1000, $cc);
}
}
// 异步dns查询修改为标准异步接口
class AsyncDns implements Async
{
public function begin(callable $cc)
{
swoole_async_dns_lookup("www.baidu.com", function($host, $ip) use($cc) {
// 这里我们会发现, 通过call $cc, 将返回值作为参数进行传递, 与callcc相像
// $ip 通过$cc 从子生成器传入父生成器, 最终通过send方法成为yield表达式结果
$cc($ip);
});
}
}
function newGen()
{
$r1 = (yield newSubGen());
$r2 = (yield 2);
$start = time();
yield new AsyncSleep();
echo time() - $start, "\n";
$ip = (yield new AsyncDns());
yield "IP: $ip";
}
$task = new AsyncTask(newGen());
$trace = function($r) { echo $r; };
$task->begin($trace);
// output:
// 1
// IP: 115.239.210.27
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论