Exploring Coroutines in PHP

https://news.ycombinator.com/rss Hits: 8
Summary

The term "coroutine" often comes up when talking about asynchronous or non-blocking code, but what does it actually mean? In this post, we will explore coroutines as a concept and see how PHP supports them through Generators and Fibers. Whether you're building pipelines, CLI tools, or preparing to dive into concurrency, understanding coroutines is an essential first step. What are Coroutines? A coroutine is a function. However, where a regular function continuously runs from top to bottom until it is finished, a coroutine can pause/suspend itself and be resumed. It can return a value every time it suspends, and receive a value when it is resumed. While the coroutine is suspended and not yet finished, it will hold on to the current state it is in. Suspend and resume Once a coroutine is executed, it will start performing its task. During the execution, the coroutine can suspend itself, handing over control to the rest of the code. This means that the suspension of the execution can only originate inside the coroutine. It has to voluntarily release control (dare I say it should yield? Spoilers!) After that, the fate of the coroutine is in the hands of the rest of the code. It cannot resume itself. The coroutine will have to be explicitly given control back with the instruction to resume. Until then, it waits while the rest of the code runs. Note: The other code could continue and never call the coroutine again, leaving it in its suspended state. Once the other code finishes, the program ends. It will not have to wait for the coroutine to finish. Return and receive values When a coroutine suspends its execution, it can provide a value to go with that. This makes the suspension like a return statement. And because a coroutine can resume and suspend multiple times, it can return multiple values. A coroutine can also receive a value when it is resumed. It will have this value available immediately after resuming and can act on it. This makes a coroutine bi-directional. Whi...

First seen: 2025-07-08 10:30

Last seen: 2025-07-08 17:31