自 2000 年 5 月 22 日 PHP4 的第一个版本发布以来,PHP 的线程模型已经存在很长时间了。
前端线程
在 Web 应用程序的前端创建用户线程没有任何意义;规模化非常困难。 Apache Worker MPM 二进制文件和 mod_php 使用的每个客户端模型的线程并不是您真正想用来为您的网站提供服务的东西,当然,如果您正在使用它,您肯定不想创建额外的线程来直接响应任何 Web 请求。
为什么前端线程是个坏主意?
您可能经常听到开发人员说前端的线程没有意义,但没有提供这种断言的理由。当您学会以所需的方式思考系统时,问题就变得显而易见了:
如果客户端脚本创建 8 个线程以直接响应 Web 请求,并且 100 个客户端同时请求该脚本,则您要求您的硬件同时执行 800 个线程。
CPU 的外观和工作方式必须非常不同才能成为一个好主意
我们能做些什么呢?
企业解决方案可能有一个面向公众的 PHP 网站,但系统的实际大脑是用可以很好地支持构建企业解决方案所需的那些语言编写的,例如 Java、C#、C++ 或任何语言当天是。
你应该以同样的方式使用 pthreads;通过设计其组件彼此分离的系统,仅通过精心设计的高性能 (RPC) API 连接,这样设计多线程架构所固有的复杂性与面向公众的网站完全隔离,并且简单,此类网站所需的可扩展设置。
你现在可以识别代码
让我们从 Hello World 开始吧:
<?php
class My extends Thread {
public function run() {
printf("Hello World\n");
}
}
/* create a new Thread */
$my = new My();
/* start the Thread */
$my->start();
/* do not allow PHP to manage the shutdown of your Threads */
/* if a variable goes out of scope in PHP it is destroyed */
/* joining explicitly ensures integrity of the data contained in an objects */
/* members while other contexts may be accessing them */
$my->join();
?>
无聊,但我希望你能读到它;)
所以在一个真实的系统中,你真的不想如此明确地创建线程,你肯定只想将任务提交给一些执行器服务,所有复杂的系统,在它们的多任务要求的意义上,我见过用这样的东西...
<?php
class My extends Threaded {
public function run() {
printf("Hello World from %s#%lu\n",
__CLASS__, Thread::getCurrentThreadId());
}
}
/* create a Pool of four threads */
/* threads in a pool are created when required */
$pool = new Pool(4);
/* submit a few tasks to the pool */
$tasks = 100;
while ($tasks--) {
$pool->submit(new My());
}
/* shutting down the pool is tantamount to joining all workers */
/* remember what I said about joining ? */
$pool->shutdown();
?>
我已经对复杂的事情进行了非常简短的解释,你应该尽力阅读:
可以在此处找到许多示例:https://github.com/krakjoe/pthreads/tree/master/examples
免责声明:使用线程的服务器架构并没有什么问题,但是当您开始创建额外的线程时,您会限制它的可扩展性和按设计执行的能力,我可以想象设计良好的架构确实有能力在前端进行线程化,但这并不是一件容易的事情。此外,对于高性能 Web 目标应用程序,线程并不是工具箱中唯一的东西。研究你所有的选择。