php如何实现并发
PHP 实现并发的方法
PHP 本身是单线程语言,但可以通过多种方式实现并发处理,提高程序性能。以下是几种常见的方法:
多进程方式(PCNTL 扩展)
使用 pcntl_fork 创建子进程,每个子进程独立执行任务。适用于 CLI 模式。
$pid = pcntl_fork();
if ($pid == -1) {
die('Could not fork');
} elseif ($pid) {
// 父进程
pcntl_wait($status); // 等待子进程结束
} else {
// 子进程
// 执行任务代码
exit();
}
多线程方式(Pthreads 扩展)
Pthreads 提供了面向对象的线程 API,但仅适用于 CLI 模式且需要 ZTS 版本的 PHP。

class MyThread extends Thread {
public function run() {
// 线程执行的代码
}
}
$thread = new MyThread();
$thread->start();
$thread->join();
异步非阻塞 I/O(Swoole 扩展)
Swoole 提供了高性能的异步并发框架,支持协程。
$server = new Swoole\Http\Server("0.0.0.0", 9501);
$server->on('Request', function($request, $response) {
// 异步任务
$response->end("Hello World");
});
$server->start();
消息队列(Gearman/RabbitMQ)
将任务放入队列,由多个 worker 进程并行处理。

$client = new GearmanClient();
$client->addServer();
$client->doBackground("job_name", "workload");
协程(Coroutine)
PHP 8.1+ 内置了 Fibers 协程支持,或使用第三方库如 ReactPHP。
$fiber = new Fiber(function() {
Fiber::suspend();
return 'Done';
});
$fiber->start();
$fiber->resume();
并行 HTTP 请求(Guzzle Async)
使用 Guzzle 的异步客户端发送多个 HTTP 请求。
$client = new GuzzleHttp\Client();
$promises = [
$client->getAsync('http://example.com'),
$client->getAsync('http://example.org')
];
$results = GuzzleHttp\Promise\unwrap($promises);
选择建议
- CLI 环境:优先考虑 PCNTL 或 Swoole
- Web 环境:推荐 Swoole 或消息队列
- 简单任务:Guzzle 异步请求足够
- 高性能需求:Swoole 协程方案最佳
每种方案都有适用场景,需根据具体业务需求选择最合适的并发实现方式。






