views:

1552

answers:

6

I recently read about http://php.net/pcntl and was woundering how good that functions works and if it would be smart to use multithreading in PHP since it isn't a core function of PHP.

I would want to trigger events that don't require feedback through it like fireing a cronjob execution manually.

All of it is supposed to run in a web app written with Zend Framework

+3  A: 

The pcntl package works quite fine - it just uses the according unix functions. The only shortage is that you can't use them if php is invoked from a web server context. i.e. you can use it in shell scripts, but not on web pages - at least not without using a hack like calling a forking script with exec or similar.

[edit] I just found a page explaining why mod_php cannot fork. Basically it's a security issue. [/edit]

soulmerge
damn it I wanted to use it in a webapp :(
Thomaschaaf
+1  A: 

The only possible way to have php code executing in multiple threads is to run php as a module of a threaded web server, which is useless because threads are fully isolated and your code has no control over them. As far as i know, pcntl only manages processes, not threads.

RommeDeSerieux
+2  A: 

This is not thread control, this is process control. The library for the threads is pthreads (POSIX threads) and it's not included in PHP, so there are no multi-threading functions in PHP.

As of multiprocessing, you cannot use that in mod_php, as that would be a giant security hole (spawned process would have all the web-server's privileges).

vartec
+1  A: 

If I needed to do manual crontab executions or the like from PHP, I'd probably use a queue. Have a database table that you append jobs to. Another process, either from a cron or running as a daemon, executes the jobs as they show up.

Another way to do it is to set up a separate script and do an HTTP GET to it. It's not quite threading, but it's one way of shelling to another command in PHP.

For example, if I wanted to run /usr/bin/somescript.sh on demand, I'd have a somescript.php that did a system call. This would be on a virtual host only accessible from localhost.

I'd do a socket call to the webserver and GET the script. The key is to not read on the socket so it doesn't block. If I wanted to check the return value of somescript.php, I'd do it later in my main script to prevent blocking.

If somescript.php takes a long time to execute (longer than the calling script), you'll have to do some magic to stop apache from killing the script when the socket is closed.

Gary Richardson
+1  A: 

Multiplatform PHP Multithreading engine http://anton.vedeshin.com/articles/lightweight-and-multiplatform-php-multithreading-engine

A: 

Examples of multithreading working in PHP http://drupal.org/project/cron%5Fmt http://drupal.org/project/boost

mikeytown2