Running the same script at the same time and PHP's single-threaded status

PHP is NOT single threaded by nature.

http://php.net/Thread

It is, however, the case that the most common installation of PHP on unix systems is a single threaded setup, as is the most common Apache installation, and nginx doesn't have a thread based architecture whatever.

In this most common unix setup, each http server process accepting requests can do one of a few things:

  • spawn a php interpreter process (cgi - generic CGI gateway)
  • manipulate an in process instance of the interpreter (mod_php5 - apache specific PHP module, services both mpm and worker installations of Apache)
  • communicate with an FCGI process (php-fpm - commonly used with nginx, some apache usage goes on still ...)

In the most common Windows setup and some more advanced unix setups, PHP can and does operate multiple interpreter threads in one process.

In any case, each instance of the interpreter, be it in another process or in another thread, has access to a unique representation of the script that is a result of compiling the PHP script into opcodes for execution by Zend.

This is by design, it's referred to as a shared nothing architecture and it is the thing allowing you to create hundreds/thousands/millions of instances of the same script that for the most part do not interfere with each other.

Even where PHP utilizes opcode caching to save resources on the compilation stage of execution, no two instances of the interpreter access the same physical memory.

Noteworthy: PHP is not completely void of the effects of concurrent execution in any setup, this is the nature of modern computing; for example if your script edits a text file, and 1000 clients come at once, what do you think will happen to the text file ?


The single threaded nature of PHP means that PHP doesn't have any built-in support for spawning new threads during script execution.

However, this doesn't mean that you can't have two executions of the same script simultanously.

In the most common setup, your website is served by Apache HTTPD. When an HTTP request for a particular script comes in (e.g. /news.php, Apache executes the script and returns the result. While the script itself cannot launch new threads, Apache itself happily forks whole new processes to service multiple HTTP requests simultanously.

Update

Please see Joe Watkins answer. It appears that PHP indeed does have support for creating threads during execution. However, this doesn't change that fact that you can have simultanous executions of the same script.