且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Symfony2 中的多线程

更新时间:2023-01-09 16:54:03

PHP 确实做多线程,pthread 的文档可以找到:http://php.net/pthreads

PHP does do multithreading, the documentation for pthreads can be found: http://php.net/pthreads

许多用法示例:https://github.com/krakjoe/pthreads/tree/master/examples

它不像简单地创建一个线程并允许它在您完成对请求的服务时在后台执行,虽然您可以通过与服务请求的主线程分离来做到这一点,但这不是一个好主意.

It is not as simple as simple create a thread and allow it to execute in the background while you finish servicing the request, while you could do that by detaching from the main thread servicing the request, it's not a very good idea.

您永远不想创建任何线程来直接响应 Web 请求,因为这只能扩展到目前为止.您想要做的是将您需要不断运行的应用程序部分分开,而不管网站的前端部分在做什么.我们将应用程序的这个新分离的部分称为后端.应用的后端应该是一个一直运行的服务,独立于apache、fpm或者nginx.很可能使用多线程来最大化后端服务的吞吐量,您仍然需要一些简单的前后端通信方式;unix 域套接字、tcp 套接字等. 通过应用程序前端和后端之间的通信通道,前端可以传递数据并指示后端以任何适当的形式将事务排队,而前端则不必等待结果.这是一个更好的设计,不一定需要任何多线程,尽管毫无疑问它是一个候选.

You never really want to create any threads in direct response to a web request, since this can only scale so far. What you want to do instead is separate that part of the application which you require to run constantly and regardless of what the front end parts of the website are doing. This newly separated part of the application we'll refer to as the back end. The back end of the application should be a service that runs all the time, independently of apache, fpm, or nginx. It very well may use multi threading to maximize throughput of the back end services, you will still need some simple way for the front and back ends to communicate; unix domain sockets, tcp sockets etc. With a communication channel between the front and back ends of your application, the front end can pass data and instruct the back end to queue transactions in whatever form is appropriate while the front end never has to wait for a result. This is a much better design, that doesn't necessarily require any multi-threading, although no doubt it's a candidate.

重要的是要记住,向某事扔线程并不一定会使事情变得更好,唯一可以肯定的是它会更忙,性能不是默认使用的产品,您必须考虑仔细考虑如何使用资源、如何在应用程序的组成部分之间进行通信,以及如何使用最少的线程(或实际上是进程)来获得最大的吞吐量.

It is important to remember that throwing threads at something doesn't necessarily make anything better, the only thing you can say for sure is that it will be busier, performance is not a product of use by default, you have to think carefully about how you will use resources, how you will communicate between the component parts of your application, and how to use the minimum number of threads (or indeed, processes) for the maximum amount of throughput.