Home > Backend Development > PHP Tutorial > Detailed explanation of cooperative multi-tasking in PHP

Detailed explanation of cooperative multi-tasking in PHP

小云云
Release: 2023-03-21 17:36:02
Original
1539 people have browsed it

One of the better new features of PHP5.5 is the support for generators and coroutines. Generators are already covered in great detail in PHP's documentation and various other blog posts (like this one or this one). Coroutines have received relatively little attention, so although coroutines have very powerful functions, they are difficult to know and difficult to explain.

Generator

The most basic idea of ​​a generator is also a function. The return value of this function is output in sequence, rather than just returning a single value. Or, in other words, generators make it easier for you to implement the iterator interface. The following is a simple explanation by implementing an xrange function:

7b790c7a9001bebd1a83f47aea376ec6

结束语

在这篇文章里,我使用多任务协作构建了一个任务调度器,其中包括执行“系统调用”,做非阻塞操作和处理错误。所有这些里真正很酷的事情是任务的结果代码看起来完全同步,甚至任务正在执行大量的异步操作的时候也是这样。如果你打算从套接口读取数据的话,你将不需要传递某个回调函数或者注册一个事件侦听器。相反,你只要书写yield $socket->read()。这儿大部分都是你常常也要编写的,只在它的前面增加yield。

当我第一次听到所有这一切的时候,我发现这个概念完全令人折服,而且正是这个激励我在PHP中实现了它。同时我发现协程真正令人心慌。在令人敬畏的代码和很大一堆代码之间只有单薄的一行,我认为协程正好处在这一行上。讲讲使用上面所述的方法书写异步代码是否真的有益对我来说很难。

The above is the detailed content of Detailed explanation of cooperative multi-tasking in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template