Home > Article > Backend Development > What does PHP coroutine mean?
#What does PHP coroutine mean?
PHP coroutines are equivalent to threads. Threads mean that when switching thread contexts, you must first save the context of the previous thread, and then execute the next thread. When the conditions are met, switch back to the previous thread. Threads and restore the context, the same is true for coroutines, except that coroutines are scheduled by the user, while threads are scheduled by the system.
PHP Coroutine Usage
Coroutine support is based on the iterative 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.
The function of passing data is through the send() method of the iterator Implemented. The following logger() coroutine is an example of how this communication works:
<?php function logger($fileName) { $fileHandle = fopen($fileName, 'a'); while (true) { fwrite($fileHandle, yield . "\n"); } } $logger = logger(__DIR__ . '/log'); $logger->send('Foo'); $logger->send('Bar') ?>
As you can see, here yield is not used as a statement, but as an expression, i.e. It can be evolved into a value. This value is the value passed by the caller to the send() method. In this example, the yield expression will first be replaced by "Foo" and written to Log, and then replaced by "Bar" and written to Log. .
The above example demonstrates yield as the recipient. Next, let’s look at an example of how to receive and send at the same time:
<?php function gen() { $ret = (yield 'yield1'); var_dump($ret); $ret = (yield 'yield2'); var_dump($ret); } $gen = gen(); var_dump($gen->current()); // string(6) "yield1" var_dump($gen->send('ret1')); // string(4) "ret1" (the first var_dump in gen) // string(6) "yield2" (the var_dump of the ->send() return value) var_dump($gen->send('ret2')); // string(4) "ret2" (again from within gen) // NULL (the return value of ->send()) ?>
It may be a little bit difficult to quickly understand the precise order of the output. Difficult, but you must figure out why it is output in this way so that you can continue reading.
In addition, there are two points I want to point out in particular:
First point, yield expression The brackets on both sides of the formula were not optional before PHP7, which means that parentheses are required in PHP5.5 and PHP5.6.
Second point, you may have noticed before calling current() rewind() is not called. This is because the rewind operation has been implicitly performed when generating the iteration object.
Recommended tutorial: "PHP Tutorial"
The above is the detailed content of What does PHP coroutine mean?. For more information, please follow other related articles on the PHP Chinese website!