php协程实现
PHP协程实现方法
PHP中协程的实现主要依赖于生成器(Generator)和相关的扩展库。以下是几种常见的实现方式:
使用生成器(Generator)
PHP 5.5+原生支持生成器,可以用于实现简单的协程:
function producer() {
for ($i = 0; $i < 5; $i++) {
yield $i;
}
}
function consumer($generator) {
foreach ($generator as $value) {
echo "Received: $value\n";
}
}
consumer(producer());
使用yield实现协程调度
通过yield可以实现更复杂的协程调度:
function task1() {
for ($i = 1; $i <= 3; $i++) {
echo "Task 1 iteration $i\n";
yield;
}
}
function task2() {
for ($i = 1; $i <= 5; $i++) {
echo "Task 2 iteration $i\n";
yield;
}
}
$scheduler = new SplQueue();
$scheduler->enqueue(task1());
$scheduler->enqueue(task2());
while (!$scheduler->isEmpty()) {
$task = $scheduler->dequeue();
$task->current();
if ($task->valid()) {
$scheduler->enqueue($task);
}
}
使用Swoole扩展
Swoole提供了完整的协程支持:
Swoole\Runtime::enableCoroutine();
go(function () {
$client = new Swoole\Coroutine\Http\Client('www.example.com', 80);
$client->get('/');
echo $client->body;
$client->close();
});
使用OpenSwoole扩展
OpenSwoole是Swoole的分支版本,也提供协程支持:
OpenSwoole\Runtime::enableCoroutine();
OpenSwoole\Coroutine\run(function () {
$result = OpenSwoole\Coroutine\System::exec('ls -l');
echo $result['output'];
});
使用Amphp库
Amphp是一个异步编程框架,支持协程:
Amp\Loop::run(function () {
$future1 = Amp\call(function () {
return yield someAsyncOperation();
});
$future2 = Amp\call(function () {
return yield anotherAsyncOperation();
});
$results = yield Amp\Promise\all([$future1, $future2]);
print_r($results);
});
协程通信实现
协程间可以通过Channel进行通信:

Swoole\Coroutine\run(function () {
$chan = new Swoole\Coroutine\Channel(1);
Swoole\Coroutine::create(function () use ($chan) {
$chan->push('data');
});
Swoole\Coroutine::create(function () use ($chan) {
$data = $chan->pop();
echo $data;
});
});
注意事项
- 原生PHP生成器实现的协程功能有限,适合简单场景
- Swoole/OpenSwoole提供了完整的协程支持,适合生产环境
- 协程切换时需要注意资源管理,避免内存泄漏
- 协程不适合CPU密集型任务,适合I/O密集型任务
以上方法可以根据具体需求选择适合的协程实现方案。






