php如何实现并发
PHP 实现并发的方法
PHP 本身是单线程语言,但可以通过多种方式实现并发处理任务,提高程序性能。
多进程方式(PCNTL 扩展)
使用 PHP 的 PCNTL 扩展可以创建多个子进程来并行处理任务。
$pid = pcntl_fork();
if ($pid == -1) {
die('Could not fork');
} else if ($pid) {
// 父进程
pcntl_wait($status); // 等待子进程结束
} else {
// 子进程
// 执行并发任务
exit();
}
需要注意 PCNTL 扩展只在 CLI 模式下可用,且需要有系统权限。
多线程方式(pthreads 扩展)
PHP 通过 pthreads 扩展可以实现多线程编程:

class MyThread extends Thread {
public function run() {
// 线程执行的任务
}
}
$thread = new MyThread();
$thread->start();
$thread->join();
pthreads 同样只在 CLI 模式下工作,且需要线程安全的 PHP 版本。
异步非阻塞 I/O(Swoole 扩展)
Swoole 提供了高性能的异步并发能力:
$serv = new Swoole\Http\Server("127.0.0.1", 9501);
$serv->on('Request', function($request, $response) {
// 异步任务
Swoole\Coroutine::create(function() use ($response) {
// 并发处理
$response->end("Hello World");
});
});
$serv->start();
Swoole 需要单独安装扩展,但提供了更强大的并发能力。

消息队列(RabbitMQ/Redis)
通过消息队列实现任务分发和并发处理:
// 生产者
$channel->queue_declare('task_queue', false, true, false, false);
$msg = new AMQPMessage($data, ['delivery_mode' => 2]);
$channel->basic_publish($msg, '', 'task_queue');
// 消费者
$channel->basic_consume('task_queue', '', false, false, false, false,
function($msg) {
// 处理任务
$msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
}
);
协程(Goroutine 风格)
使用协程库如 Go 风格的并发:
use Spatie\Async\Pool;
$pool = Pool::create();
foreach ($tasks as $task) {
$pool[] = async(function() use ($task) {
return $task->process();
})->then(function($output) {
// 处理结果
});
}
await($pool);
并行 HTTP 请求(Guzzle 并发)
使用 Guzzle 发起并发 HTTP 请求:
$client = new GuzzleHttp\Client();
$promises = [
$client->getAsync('http://example.com/1'),
$client->getAsync('http://example.com/2')
];
$results = GuzzleHttp\Promise\unwrap($promises);
选择建议
- CLI 环境下优先考虑 PCNTL 或 pthreads
- Web 环境下考虑 Swoole 或消息队列
- 简单任务可使用 Guzzle 并发请求
- 高性能场景推荐 Swoole 或协程方案
每种方法都有适用场景,应根据具体需求选择最合适的并发实现方式。






