Detailed explanation of php coroutine (with examples)
This article brings you a detailed explanation of PHP coroutines (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Multi-tasking (parallel and concurrency)
Before talking about coroutines, let’s talk about multi-processes, multi-threads, parallelism and concurrency.
For single-core processors, the principle of multi-process multitasking is to let the operating system allocate a certain CPU time slice to a task each time, then interrupt, let the next task execute a certain time slice, and then interrupt again And move on to the next one, and so on.
Since switching execution tasks is very fast, the impression given to external users is that multiple tasks are executed simultaneously.
The scheduling of multi-processes is implemented by the operating system. The process itself cannot control when it is scheduled. That is to say: The scheduling of processes
is performed by the outer scheduler Preemptive
implementation
The coroutine requires the currently running task to automatically pass control back to the scheduler, so that other tasks can continue to run. This is exactly the opposite of preemptive
multitasking. The scheduler of preemptive multitasking can forcefully interrupt running tasks regardless of its own wishes. If only the program were to automatically hand over control, it would be easy for some malicious program to take up all of the CPU time without sharing it with other tasks.
The scheduling of the coroutine is implemented by the coroutine itselfactively
giving up control to the outer scheduler
Back to the example of the generator implementing the xrange function, The alternation of the entire execution process can be represented by the following figure:
Coroutines can be understood as pure user-mode threads
, which perform task switching through collaboration
rather than preemption .
Compared with processes or threads, all operations of coroutines can be completed in user mode instead of operating system kernel mode, and the cost of creation and switching is very low.
Simply putCoroutine
is to provide a method to interrupt the execution of the current task, save the current local variables, and restore the current local variables to continue execution next time.
We can split the large task into multiple small tasks and execute them in turn. If there is a small task waiting for system IO, skip it and execute the next small task. In this way, we can schedule back and forth to achieve IO. The parallel execution of operations and CPU calculations generally improves the execution efficiency of tasks, which is the meaning of coroutines
Multi-threading
Under a single core, multi-threads must be concurrent;
However, the current multi-threading of the unified process can run under multi-core CPU, so it can be parallel
Concurrency (Concurrency)
refers to the ability to handle multiple simultaneous activities , concurrent events do not necessarily have to occur at the same time.
Parallel (Parallesim)
refers to two concurrent events that occur at the same time, which has the meaning of concurrency, but concurrency is not necessarily parallel.
Multiple operations can be performed within overlapping time periods.
The difference between parallelism and concurrency
Concurrency
refers to the structure of the program, Parallel
refers to the state of the program when it is runningParallel
must be concurrent, Parallel
is a type of Concurrency
design
A single thread can never reach the Parallel
state
Coroutine
Coroutine support is based on generator
, adding the function of sending data back to the generator (the caller sends data to the called generator function) .
This changes the one-way communication from the generator to the caller into a two-way communication between the two.
We have already talked about the send method in the previous article, let us understand the coroutine
Synchronous code
Before asynchronous execution code is involved, our code is like this
function printNum($max, $caller) { for ($i=0; $i<h3 id="Improved-code-after-using-coroutines">Improved code after using coroutines</h3><p>First draft, Manually adjust generator execution</p><pre class="brush:php;toolbar:false"># 本代码手动调整了进程执行代码的顺序,当然本代码实现不用协程也可以,只是利用本流程说明协程作用 # 生成器给了我们函数中断,协程[生成器send]给了我们重新唤起生成器函数的能力 function printNumWithGen($max) { for ($i=0; $isend("调度者: caller1 打印:" . $gen1->current() . PHP_EOL); $gen2->send("调度者: caller2 打印:" . $gen2->current() . PHP_EOL); // 手动执行caller1 再 caller2 $gen1->send("调度者: caller1 打印:" . $gen1->current() . PHP_EOL); $gen2->send("调度者: caller2 打印:" . $gen2->current() . PHP_EOL); // 手动执行caller2 再 caller1 $gen2->send("调度者: caller2 打印:" . $gen2->current() . PHP_EOL); $gen1->send("调度者: caller1 打印:" . $gen1->current() . PHP_EOL); # output 调度者: caller1 打印:0 调度者: caller2 打印:0 调度者: caller1 打印:1 调度者: caller2 打印:1 调度者: caller2 打印:2 调度者: caller1 打印:2
Summary
The above case should let everyone understand the meaning of coroutine design and how to use coroutines
Then let’s automatically create one for our coroutine Automatic scheduler (Co automatic executor), no need to manually interrupt and resume
The above is the detailed content of Detailed explanation of php coroutine (with examples). For more information, please follow other related articles on the PHP Chinese website!

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

Fibers was introduced in PHP8.1, improving concurrent processing capabilities. 1) Fibers is a lightweight concurrency model similar to coroutines. 2) They allow developers to manually control the execution flow of tasks and are suitable for handling I/O-intensive tasks. 3) Using Fibers can write more efficient and responsive code.

The PHP community provides rich resources and support to help developers grow. 1) Resources include official documentation, tutorials, blogs and open source projects such as Laravel and Symfony. 2) Support can be obtained through StackOverflow, Reddit and Slack channels. 3) Development trends can be learned by following RFC. 4) Integration into the community can be achieved through active participation, contribution to code and learning sharing.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version
Chinese version, very easy to use