PHP 有线程吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/209774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:56:38  来源:igfitidea点击:

Does PHP have threading?

phpmultithreadingapachecommand-line-interface

提问by Thomas Owens

I found this PECL package called threads, but there is not a release yet. And nothing is coming up on the PHP website.

我找到了这个名为 thread 的 PECL 包,但还没有发布。PHP 网站上没有任何内容。

采纳答案by Wilco

There is nothing available that I'm aware of. The next best thing would be to simply have one script execute another via CLI, but that's a bit rudimentary. Depending on what you are trying to do and how complex it is, this may or may not be an option.

我不知道有什么可用的。下一个最好的方法是简单地让一个脚本通过 CLI 执行另一个脚本,但这有点初级。根据您要尝试做什么以及它的复杂程度,这可能是也可能不是一个选项。

回答by Joe Watkins

From the PHP manual for the pthreadsextension:

来自pthreads扩展的 PHP 手册:

pthreads is an Object Orientated API that allows user-land multi-threading in PHP. It includes all the tools you need to create multi-threaded applications targeted at the Web or the Console. PHP applications can create, read, write, execute and synchronize with Threads, Workers and Stackables.

pthreads 是一个面向对象的 API,它允许 PHP 中的用户级多线程。它包括创建面向 Web 或控制台的多线程应用程序所需的所有工具。PHP 应用程序可以创建、读取、写入、执行和同步线程、工作线程和堆栈。

As unbelievable as this sounds, it's entirely true. Today, PHP can multi-thread for those wishing to try it.

尽管这听起来令人难以置信,但这完全是真的。今天,PHP 可以为那些希望尝试它的人提供多线程。

The first release of PHP4, 22 May 2000, PHP was shipped with a thread safe architecture - a way for it to execute multiple instances of it's interpreter in separate threads in multi-threaded SAPI ( Server API ) environments. Over the last 13 years, the design of this architecture has been maintained and advanced: It has been in production use on the worlds largest websites ever since.

PHP4 的第一个版本,2000 年 5 月 22 日,PHP 附带了一个线程安全架构——一种在多线程 SAPI(服务器 API)环境中在单独的线程中执行它的解释器的多个实例的方法。在过去的 13 年中,这种架构的设计一直得到维护和改进:从那时起,它一直在世界上最大的网站上投入生产使用。

Threading in user land was never a concern for the PHP team, and it remains as such today. You should understand that in the world where PHP does it's business, there's already a defined method of scaling - add hardware. Over the many years PHP has existed, hardware has got cheaper and cheaper and so this became less and less of a concern for the PHP team. While it was getting cheaper, it also got much more powerful; today, our mobile phones and tablets have dual and quad core architectures and plenty of RAM to go with it, our desktops and servers commonly have 8 or 16 cores, 16 and 32 gigabytes of RAM, though we may not always be able to have two within budget and having two desktops is rarely useful for most of us.

用户空间中的线程从来不是 PHP 团队关心的问题,今天仍然如此。您应该明白,在 PHP 开展业务的世界中,已经有一种已定义的扩展方法 - 添加硬件。PHP 存在多年以来,硬件变得越来越便宜,因此 PHP 团队越来越不关心这个问题。虽然它变得越来越便宜,但它也变得更加强大。今天,我们的手机和平板电脑具有双核和四核架构以及大量 RAM,我们的台式机和服务器通常具有 8 或 16 核、16 和 32 GB 的 RAM,尽管我们可能并不总是能够拥有两个在预算范围内并拥有两个桌面对我们大多数人来说很少有用。

Additionally, PHP was written for the non-programmer, it is many hobbyists native tongue. The reason PHP is so easily adopted is because it is an easy language to learn and write. The reason PHP is so reliable today is because of the vast amount of work that goes into it's design, and every single decision made by the PHP group. It's reliability and sheer greatness keep it in the spot light, after all these years; where it's rivals have fallen to time or pressure.

此外,PHP 是为非程序员编写的,它是许多爱好者的母语。PHP 之所以如此容易被采用,是因为它是一种易于学习和编写的语言。PHP 在今天如此可靠的原因在于其设计中的大量工作,以及 PHP 小组做出的每一个决定。经过这么多年,它的可靠性和绝对的伟大使它成为人们关注的焦点。那里的竞争对手已经落入时间或压力。

Multi-threaded programming is not easy for most, even with the most coherent and reliable API, there are different things to think about, and many misconceptions. The PHP group do not wish for user land multi-threading to be a core feature, it has never been given serious attention - and rightly so. PHP should not be complex, for everyone.

多线程编程对大多数人来说并不容易,即使有最连贯、最可靠的 API,也有不同的事情需要考虑,也有很多误解。PHP 组不希望用户端多线程成为核心功能,它从未受到过认真的关注——这是正确的。PHP 不应该复杂,适合每个人。

All things considered, there are still benefits to be had from allowing PHP to utilize it's production ready and tested features to allow a means of making the most out of what we have, when adding more isn't always an option, and for a lot of tasks is never really needed.

考虑到所有因素,允许 PHP 利用它的生产就绪和经过测试的功能仍然有好处,可以充分利用我们拥有的东西,当添加更多并不总是一种选择时,而且很多任务从来都不是真正需要的。

pthreads achieves, for those wishing to explore it, an API that does allow a user to multi-thread PHP applications. It's API is very much a work in progress, and designated a beta level of stability and completeness.

对于那些希望探索它的人,pthreads 实现了一个允许用户多线程 PHP 应用程序的 API。它的 API 正在大量开发中,并指定了 beta 级别的稳定性和完整性。

It is common knowledge that some of the libraries PHP uses are not thread safe, it should be clear to the programmer that pthreads cannot change this, and does not attempt to try. However, any library that is thread safe is useable, as in any other thread safe setup of the interpreter.

众所周知,PHP 使用的一些库不是线程安全的,程序员应该清楚 pthreads 无法改变这一点,并且不会尝试尝试。但是,任何线程安全的库都是可用的,就像在解释器的任何其他线程安全设置中一样。

pthreads utilizes Posix Threads ( even in Windows ), what the programmer creates are real threads of execution, but for those threads to be useful, they must be aware of PHP - able to execute user code, share variables and allow a useful means of communication ( synchronization ). So every thread is created with an instance of the interpreter, but by design, it's interpreter is isolated from all other instances of the interpreter - just like multi-threaded Server API environments. pthreads attempts to bridge the gap in a sane and safe way. Many of the concerns of the programmer of threads in C just aren't there for the programmer of pthreads, by design, pthreads is copy on read and copy on write ( RAM is cheap ), so no two instances ever manipulate the same physical data, but they can both affect data in another thread. The fact that PHP may use thread unsafe features in it's core programming is entirely irrelevant, user threads, and it's operations are completely safe.

pthreads 使用 Posix 线程(即使在 Windows 中),程序员创建的是真正的执行线程,但要使这些线程有用,他们必须了解 PHP - 能够执行用户代码、共享变量并允许有用的通信方式(同步)。所以每个线程都是用解释器的一个实例创建的,但根据设计,它的解释器与解释器的所有其他实例是隔离的——就像多线程服务器 API 环境一样。pthreads 试图以一种理智和安全的方式弥合差距。C 中的线程程序员的许多担忧对于 pthreads 的程序员来说并不存在,按照设计,pthreads 是读取时复制和写入时复制(RAM 很便宜),因此没有两个实例操作相同的物理数据,但它们都可以影响另一个线程中的数据。

Why copy on read and copy on write:

为什么读时复制和写时复制:

public function run() {
    ...
    (1) $this->data = $data;
    ...
    (2) $this->other = someOperation($this->data);
    ...
}

(3) echo preg_match($pattern, $replace, $thread->data);

(1) While a read, and write lock are held on the pthreads object data store, data is copied from its original location in memory to the object store. pthreads does not adjust the refcount of the variable, Zend is able to free the original data if there are no further references to it.

(1) 在 pthreads 对象数据存储上持有读取和写入锁定时,数据会从其在内存中的原始位置复制到对象存储中。pthreads 不会调整变量的引用计数,如果没有进一步的引用,Zend 能够释放原始数据。

(2) The argument to someOperation references the object store, the original data stored, which it itself a copy of the result of (1), is copied again for the engine into a zval container, while this occurs a read lock is held on the object store, the lock is released and the engine can execute the function. When the zval is created, it has a refcount of 0, enabling the engine to free the copy on completion of the operation, because no other references to it exist.

(2) someOperation 的参数引用对象存储,存储的原始数据,它本身是 (1) 结果的副本,为引擎再次复制到 zval 容器中,同时发生读取锁定对象存储,锁被释放,引擎可以执行函数。创建 zval 时,它的引用计数为 0,使引擎能够在操作完成时释放副本,因为不存在对其的其他引用。

(3) The last argument to preg_match references the data store, a read lock is obtained, the data set in (1) is copied to a zval, again with a refcount of 0. The lock is released, The call to preg_match operates on a copy of data, that is itself a copy of the original data.

(3) preg_match 的最后一个参数引用了数据存储,获得了一个读锁,将(1)中设置的数据复制到一个zval,再次引用计数为0。锁被释放,对preg_match的调用操作数据的副本,它本身就是原始数据的副本。

Things to know:

须知:

  • The object store's hash table where data is stored, thread safe, is
    based on the TsHashTable shipped with PHP, by Zend.

  • The object store has a read and write lock, an additional access lock is provided for the TsHashTable such that if requires ( and it does, var_dump/print_r, direct access to properties as the PHP engine wants to reference them ) pthreads can manipulate the TsHashTable outside of the defined API.

  • The locks are only held while the copying operations occur, when the copies have been made the locks are released, in a sensible order.

  • 对象存储的哈希表存储数据,线程安全,
    基于 Zend 随 PHP 提供的 TsHashTable。

  • 对象存储具有读和写锁,为 TsHashTable 提供了一个额外的访问锁,这样如果需要(并且确实如此,var_dump/print_r,直接访问属性,因为 PHP 引擎想要引用它们)pthreads 可以操作 TsHashTable在定义的 API 之外。

  • 只有在复制操作发生时才会持有锁,当复制完成后,锁才会以合理的顺序被释放。

This means:

这意味着:

  • When a write occurs, not only are a read and write lock held, but an additional access lock. The table itself is locked down, there is no possible way another context can lock, read, write or affect it.

  • When a read occurs, not only is the read lock held, but the additional access lock too, again the table is locked down.

  • 发生写入时,不仅持有读写锁,还持有额外的访问锁。表本身被锁定,其他上下文不可能锁定、读取、写入或影响它。

  • 当读取发生时,不仅读取锁被持有,而且额外的访问锁也被持有,表再次被锁定。

No two contexts can physically nor concurrently access the same data from the object store, but writes made in any context with a reference will affect the data read in any context with a reference.

没有两个上下文可以物理地或同时访问对象存储中的相同数据,但是在任何带有引用的上下文中进行的写入都会影响在带有引用的任何上下文中读取的数据。

This is shared nothing architecture and the only way to exist is co-exist. Those a bit savvy will see that, there's a lot of copying going on here, and they will wonder if that is a good thing. Quite a lot of copying goes on within a dynamic runtime, that's the dynamics of a dynamic language. pthreads is implemented at the level of the object, because good control can be gained over one object, but methods - the code the programmer executes - have another context, free of locking and copies - the local method scope. The object scope in the case of a pthreads object should be treated as a way to share data among contexts, that is it's purpose. With this in mind you can adopt techniques to avoid locking the object store unless it's necessary, such as passing local scope variables to other methods in a threaded object rather than having them copy from the object store upon execution.

这是一种无共享架构,唯一存在的方式就是共存。那些有点精明的人会看到,这里有很多抄袭,他们会想知道这是否是一件好事。在动态运行时中进行了大量复制,这就是动态语言的动态。pthreads 是在对象级别实现的,因为可以获得对一个对象的良好控制,但是方法——程序员执行的代码——有另一个上下文,没有锁定和复制——本地方法范围。在 pthreads 对象的情况下,对象范围应该被视为在上下文之间共享数据的一种方式,这就是它的目的。考虑到这一点,除非必要,否则您可以采用避免锁定对象存储的技术,

Most of the libraries and extensions available for PHP are thin wrappers around 3rd parties, PHP core functionality to a degree is the same thing. pthreads is not a thin wrapper around Posix Threads; it is a threading API based on Posix Threads. There is no point in implementing Threads in PHP that it's users do not understand or cannot use. There's no reason that a person with no knowledge of what a mutex is or does should not be able to take advantage of all that they have, both in terms of skill, and resources. An object functions like an object, but wherever two contexts would otherwise collide, pthreads provides stability and safety.

大多数可用于 PHP 的库和扩展都是围绕 3rd 方的瘦包装器,PHP 核心功能在某种程度上是相同的。pthreads 不是 Posix Threads 的薄包装;它是一个基于 Posix Threads 的线程 API。在 PHP 中实现用户不理解或无法使用的线程是没有意义的。一个不知道互斥锁是什么或做什么的人没有理由不能够利用他们在技能和资源方面拥有的一切。一个对象的功能就像一个对象,但在两个上下文可能发生冲突的地方,pthreads 提供了稳定性和安全性。

Anyone who has worked in java will see the similarities between a pthreads object and threading in java, those same people will have no doubt seen an error called ConcurrentModificationException - as it sounds an error raised by the java runtime if two threads write the same physical data concurrently. I understand why it exists, but it baffles me that with resources as cheap as they are, coupled with the fact the runtime is able to detect the concurrency at the exact and only time that safety could be achieved for the user, that it chooses to throw a possibly fatal error at runtime rather than manage the execution and access to the data.

任何在 java 中工作过的人都会看到 pthreads 对象和 java 中的线程之间的相似之处,这些人无疑会看到一个名为 ConcurrentModificationException 的错误——因为如果两个线程写入相同的物理数据,这听起来是由 java 运行时引发的错误同时。我理解它为什么存在,但让我感到困惑的是,资源如此便宜,再加上运行时能够在准确且唯一的时间检测并发性,它选择为用户实现安全在运行时抛出可能致命的错误,而不是管理执行和对数据的访问。

No such stupid errors will be emitted by pthreads, the API is written to make threading as stable, and compatible as is possible, I believe.

我相信 pthread 不会发出这种愚蠢的错误,编写 API 是为了使线程尽可能稳定和兼容。

Multi-threading isn't like using a new database, close attention should be paid to every word in the manual and examples shipped with pthreads.

多线程不像使用新的数据库,应该密切关注手册中的每一个字和 pthreads 附带的示例。

Lastly, from the PHP manual:

最后,来自 PHP 手册:

pthreads was, and is, an experiment with pretty good results. Any of its limitations or features may change at any time; that is the nature of experimentation. It's limitations - often imposed by the implementation - exist for good reason; the aim of pthreads is to provide a useable solution to multi-tasking in PHP at any level. In the environment which pthreads executes, some restrictions and limitations are necessary in order to provide a stable environment.

pthreads 过去是,现在也是,一个取得相当不错结果的实验​​。其任何限制或功能可能随时更改;这就是实验的本质。它的局限性 - 通常由实施强加 - 存在是有充分理由的;pthreads 的目的是为 PHP 中任何级别的多任务提供一个可用的解决方案。在pthreads执行的环境中,为了提供一个稳定的环境,一些限制和限制是必要的。

回答by Darryl Hein

Here is an example of what Wilco suggested:

以下是 Wilco 建议的示例:

$cmd = 'nohup nice -n 10 /usr/bin/php -c /path/to/php.ini -f /path/to/php/file.php action=generate var1_id=23 var2_id=35 gen_id=535 > /path/to/log/file.log & echo $!';
$pid = shell_exec($cmd);

Basically this executes the PHP script at the command line, but immediately returns the PID and then runs in the background. (The echo $! ensures nothing else is returned other than the PID.) This allows your PHP script to continue or quit if you want. When I have used this, I have redirected the user to another page, where every 5 to 60 seconds an AJAX call is made to check if the report is still running. (I have a table to store the gen_id and the user it's related to.) The check script runs the following:

基本上这会在命令行执行 PHP 脚本,但会立即返回 PID,然后在后台运行。( echo $! 确保除了 PID 之外不返回任何其他内容。)这允许您的 PHP 脚本根据需要继续或退出。当我使用它时,我将用户重定向到另一个页面,其中每 5 到 60 秒进行一次 AJAX 调用以检查报告是否仍在运行。(我有一个表来存储 gen_id 和与之相关的用户。)检查脚本运行以下内容:

exec('ps ' . $pid , $processState);
if (count($processState) < 2) {
     // less than 2 rows in the ps, therefore report is complete
}

There is a short post on this technique here: http://nsaunders.wordpress.com/2007/01/12/running-a-background-process-in-php/

这里有一篇关于此技术的简短帖子:http: //nsaunders.wordpress.com/2007/01/12/running-a-background-process-in-php/

回答by Francois Bourgeois

In short: yes, there is multithreading in php but you should use multiprocessing instead.

简而言之:是的,php 中有多线程,但您应该改用多处理。

Backgroud info: threads vs. processes

背景信息:线程与进程

There is always a bit confusion about the distinction of threads and processes, so i'll shortly describe both:

关于线程和进程的区别总是有点混乱,所以我将简要描述两者:

  • A threadis a sequence of commands that the CPU will process. The only data it consists of is a program counter. Each CPU core will only process one thread at a time but can switch between the execution of different ones via scheduling.
  • A processis a set of shared resources. That means it consists of a part of memory, variables, object instances, file handles, mutexes, database connections and so on. Each process also contains one or more threads. All threads of the same process share its resources, so you may use a variable in one thread that you created in another. If those threads are parts of two different processes, then they cannot access each others resources directly. In this case you need inter-process communicationthrough e.g. pipes, files, sockets...
  • 线程是CPU将处理命令序列。它包含的唯一数据是程序计数器。每个 CPU 核一次只能处理一个线程,但可以通过调度在不同的执行之间切换。
  • 过程是一组共享资源。这意味着它由一部分内存、变量、对象实例、文件句柄、互斥锁、数据库连接等组成。每个进程还包含一个或多个线程。同一进程的所有线程共享其资源,因此您可以在一个线程中使用在另一个线程中创建的变量。如果这些线程是两个不同进程的一部分,那么它们就不能直接访问彼此的资源。在这种情况下,您需要通过管道、文件、套接字等进行进程间通信...

Multiprocessing

多处理

You can achieve parallel computing by creating new processes (that also contain a new thread) with php. If your threads do not need much communication or synchronization, this is your choice, since the processes are isolated and cannot interfere with each other's work. Even if one crashes, that doesn't concern the others. If you do need much communication, you should read on at "multithreading" or - sadly - consider using another programming language, because inter-process communication and synchronization introduces a lot of complexion.

您可以通过使用 php 创建新进程(也包含一个新线程)来实现并行计算。如果您的线程不需要太多的通信或同步,这是您的选择,因为进程是隔离的,不会干扰彼此的工作。即使一个崩溃,这与其他人无关。如果您确实需要大量通信,则应该继续阅读“多线程”,或者——遗憾的是——考虑使用另一种编程语言,因为进程间通信和同步会带来很多复杂性。

In php you have two ways to create a new process:

在 php 中,您有两种方法可以创建新进程:

let the OS do it for you: you can tell your operation system to create a new process and run a new (or the same) php script in it.

让操作系统为您完成:您可以告诉您的操作系统创建一个新进程并在其中运行一个新的(或相同的)php 脚本。

  • for linuxyou can use the following or consider Darryl Hein's answer:

    $cmd = 'nice php script.php 2>&1 & echo $!';
    pclose(popen($cmd, 'r'));
    
  • for windowsyou may use this:

    $cmd = 'start "processname" /MIN /belownormal cmd /c "script.php 2>&1"';
    pclose(popen($cmd, 'r'));
    
  • 对于linux,您可以使用以下内容或考虑Darryl Hein 的回答

    $cmd = 'nice php script.php 2>&1 & echo $!';
    pclose(popen($cmd, 'r'));
    
  • 对于Windows,您可以使用它:

    $cmd = 'start "processname" /MIN /belownormal cmd /c "script.php 2>&1"';
    pclose(popen($cmd, 'r'));
    

do it yourself with a fork: php also provides the possibility to use forking through the function pcntl_fork(). A good tutorial on how to do this can be found herebut i strongly recommend not to use it, since fork is a crime against humanityand especially against oop.

用 fork 自己做:php 还提供了通过pcntl_fork()函数使用 fork 的可能性。关于如何做到这一点的一个很好的教程可以在这里找到但我强烈建议不要使用它,因为fork 是一种危害人类的犯罪,尤其是对 oop的犯罪

Multithreading

多线程

With multithreading all your threads share their resources so you can easily communicate between and synchronize them without a lot of overhead. On the other side you have to know what you are doing, since race conditions and deadlocks are easy to produce but very difficult to debug.

通过多线程,您的所有线程都共享它们的资源,因此您可以轻松地在它们之间进行通信和同步,而不会产生大量开销。另一方面,您必须知道自己在做什么,因为竞争条件和死锁很容易产生但很难调试。

Standard php does not provide any multithreading but there is an (experimental) extension that actually does - pthreads. Its api documentation even made it into php.net. With it you can do some stuff as you can in real programming languages:-) like this:

标准 php 不提供任何多线程,但有一个(实验性)扩展实际上提供了 - pthreads。它的 api 文档甚至变成了php.net。有了它,你可以像在真正的编程语言中一样做一些事情:-) 像这样:

class MyThread extends Thread {
    public function run(){
        //do something time consuming
    }
}

$t = new MyThread();
if($t->start()){
    while($t->isRunning()){
        echo ".";
        usleep(100);
    }
    $t->join();
}

For linuxthere is an installation guideright here at stackoverflow's.

对于linux,stackoverflow 上有一个安装指南

For windowsthere is one now:

对于Windows,现在有一个:

  • First you need the thread-safe version of php.
  • You need the pre-compiled versions of both pthreads and its php extension. They can be downloaded here. Make sure that you download the version that is compatible with your php version.
  • Copy php_pthreads.dll (from the zip you just downloaded) into your php extension folder ([phpDirectory]/ext).
  • Copy pthreadVC2.dll into [phpDirectory] (the root folder - not the extension folder).
  • Edit [phpDirectory]/php.ini and insert the following line

    extension=php_pthreads.dll
    
  • Test it with the script above with some sleep or something right there where the comment is.

  • 首先,您需要线程安全版本的 php。
  • 您需要 pthreads 及其 php 扩展的预编译版本。它们可以在这里下载。确保您下载与您的 php 版本兼容的版本。
  • 将 php_pthreads.dll(来自您刚刚下载的 zip)复制到您的 php 扩展文件夹 ([phpDirectory]/ext)。
  • 将 pthreadVC2.dll 复制到 [phpDirectory](根文件夹 - 不是扩展文件夹)。
  • 编辑 [phpDirectory]/php.ini 并插入以下行

    extension=php_pthreads.dll
    
  • 用上面的脚本测试一下,睡眠或评论所在的地方。

And now the big BUT: Although this really works, php wasn't originally made for multithreading. There exists a thread-safe version of php and as of v5.4 it seems to be nearly bug-free but using php in a multi-threaded environment is still discouraged in the php manual(but maybe they just did not update their manual on this, yet). A much bigger problem might be that a lot of common extensions are not thread-safe. So you might get threads with this php extension but the functions you're depending on are still not thread-safe so you will probably encounter race conditions, deadlocks and so on in code you did not write yourself...

而现在的大BUT:虽然这还真管用,PHP最初不是为多线程做。存在一个线程安全的 php 版本,从 v5.4 开始,它似乎几乎没有错误,但是php 手册中仍然不鼓励在多线程环境中使用 php(但也许他们只是没有更新他们的手册)这个,还)。一个更大的问题可能是许多常见的扩展不是线程安全的。因此,您可能会使用此 php 扩展获得线程,但您所依赖的函数仍然不是线程安全的,因此您可能会在不是自己编写的代码中遇到竞争条件、死锁等...

回答by davr

You can use pcntl_fork()to achieve something similar to threads. Technically it's separate processes, so the communication between the two is not as simple with threads, and I believe it will not work if PHP is called by apache.

您可以使用pcntl_fork()来实现类似于线程的功能。从技术上讲它是独立的进程,所以两者之间的通信没有线程那么简单,我相信如果PHP被apache调用,它不会起作用。

回答by Alec Gorge

If anyone cares, I have revived php_threading(not the same as threads, but similar) and I actually have it to the point where it works (somewhat) well!

如果有人关心,我已经恢复了php_threading(与线程不同,但类似)并且我实际上已经达到了它(有点)运行良好的程度!

Project page

项目页面

Download (for Windows PHP 5.3 VC9 TS)

下载(适用于 Windows PHP 5.3 VC9 TS)

Examples

例子

README

自述文件

回答by The Surrican

pcntl_fork()is what you are searching for, but its process forking not threading. so you will have the problem of data exchange. to solve them you can use phps semaphore functions ( http://www.php.net/manual/de/ref.sem.php) message queues may be a bit easier for the beginning than shared memory segments.

pcntl_fork()是你正在寻找的,但它的进程分叉不是线程。所以你会有数据交换的问题。要解决它们,您可以使用 phps 信号量函数(http://www.php.net/manual/de/ref.sem.php)消息队列可能比共享内存段更容易开始。

Anyways, a strategy i am using in a web framework that i am developing which loads resource intensive blocks of a web page (probably with external requests) parallel: i am doing a job queue to know what data i am waiting for and then i fork off the jobs for every process. once done they store their data in the apc cache under a unique key the parent process can access. once every data is there it continues. i am using simple usleep()to wait because inter process communication is not possible in apache (children will loose the connection to their parents and become zombies...). so this brings me to the last thing: its important to self kill every child! there are as well classes that fork processes but keep data, i didn't examine them but zend framework has one, and they usually do slow but reliably code. you can find it here: http://zendframework.com/manual/1.9/en/zendx.console.process.unix.overview.htmli think they use shm segments! well last but not least there is an error on this zend website, minor mistake in the example.

无论如何,我正在开发的 Web 框架中使用的一种策略是并行加载网页的资源密集型块(可能带有外部请求):我正在做一个作业队列以了解我在等待什么数据,然后我分叉关闭每个流程的工作。完成后,它们会将数据存储在父进程可以访问的唯一键下的 apc 缓存中。一旦每个数据都在那里,它就会继续。我正在使用简单usleep()的等待,因为在 apache 中不可能进行进程间通信(孩子们将失去与父母的连接并成为僵尸......)。所以这让我想到最后一件事:自我杀死每个孩子很重要!也有分叉进程但保留数据的类,我没有检查它们,但 Zend 框架有一个,它们通常执行缓慢但可靠的代码。你可以在这里找到它: http://zendframework.com/manual/1.9/en/zendx.console.process.unix.overview.html我认为他们使用 shm 段!最后但并非最不重要的是,这个 Zend 网站上有一个错误,示例中的小错误。

while ($process1->isRunning() && $process2->isRunning()) {
    sleep(1);
}
should of course be:
while ($process1->isRunning() || $process2->isRunning()) {
    sleep(1);
}

回答by JasonDavis

There is a Threading extension being activley developed based on PThreads that looks very promising at https://github.com/krakjoe/pthreads

https://github.com/krakjoe/pthreads上有一个基于 PThreads 的 Threading 扩展正在被 activley 开发,看起来非常有前途

回答by happyhardik

Just an update, its seem that PHP guys are working on supporting thread and its available now.

只是一个更新,似乎 PHP 人员正在努力支持线程并且它现在可用。

Here is the link to it: http://php.net/manual/en/book.pthreads.php

这是它的链接:http: //php.net/manual/en/book.pthreads.php

回答by Jamie Carl

I have a PHP threading class that's been running flawlessly in a production environment for over two years now.

我有一个 PHP 线程类,它已经在生产环境中完美运行了两年多。

EDIT: This is now available as a composer library and as part of my MVC framework, Hazaar MVC.

编辑:这现在可用作作曲家库和我的 MVC 框架 Hazaar MVC 的一部分。

See: https://git.hazaarlabs.com/hazaar/hazaar-thread

请参阅:https: //git.hazaarlabs.com/hazaar/hazaar-thread