自 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://gist.github.com/krakjoe/6437782 https://gist.github.com/krakjoe/6437782
- https://gist.github.com/krakjoe/9384409 https://gist.github.com/krakjoe/9384409
- http://php.net/pthreads http://php.net/pthreads
许多例子可以在这里找到:https://github.com/krakjoe/pthreads/tree/master/examples https://github.com/krakjoe/pthreads/tree/master/examples
免责声明:使用线程的服务器架构并没有什么问题,但是当您开始创建额外的线程时,您就限制了它的可扩展性和按照设计执行的能力,我可以想象设计良好的架构确实具有线程的能力在前端,但要实现这一目标并不是一件容易的事。此外,当涉及高性能 Web 目标应用程序时,线程并不是工具箱中唯一的东西。研究你所有的选择。