3

Is there a way to achieve inter-process (or threading) communication in PHP, but still keep everything run asynchronous?

I want to have a script that creates 4 processes and then terminates immediately. Each of the 4 processes should do an action and when finished it should notify someone (another script maybe?) that it finished. So I want to know when all of the 4 scripts are done, so I can update my status from retrieving to done.

Is this possible? Preferably without re-compiling PHP (I read this is required for working with threads), but I will do that if necessary.

Eduard Luca
  • 6,514
  • 16
  • 85
  • 137
  • Why is it necessary that the script creating the process terminates immediately? – Michael Mior Jan 03 '12 at 11:33
  • `Preferably without re-compiling PHP (I read this is required for working with threads)` - really? Where? AFAIK it is not possible to multithread PHP, and if you have found a way I would dearly love to know about it... – DaveRandom Jan 03 '12 at 11:36
  • @MichaelMior: because I don't want the user to have to wait until the 4 sub-scripts finish, as they take a lot of time. @DaveRandom: no, native multi-threading is not supported, but http://blog.motane.lu/2009/01/02/multithreading-in-php/ shows how to emulate them, but PHP needs to be re-compiled for `pcntl_fork` to work. – Eduard Luca Jan 03 '12 at 11:44
  • Then you can simply use `ignore_user_abort()` and flush the output to the browser to allow the script to continue in the background. – Michael Mior Jan 03 '12 at 11:46
  • Take a look a this [post][1] It worked for me [1]: http://stackoverflow.com/a/13690590/599993 – jzafrilla Dec 04 '12 at 09:00

3 Answers3

4

As others have mentioned, Gearman is one solution. The other, one I actually prefer, is creating an asynchronous message queue where you add jobs on the job stack.

I'm using ZeroMQ for such purposes, and there's a PHP framework available that implements ZeroMQ for async tasks called Photon. Browsing Photon's source might give you some ideas on how to implement async job queue in case you decide to go with it.

N.B.
  • 13,688
  • 3
  • 45
  • 55
2

Gearman may provide what you are looking for.

Jeremy Harris
  • 24,318
  • 13
  • 79
  • 133
1

You can use a job queueing system or stick it into CRON. PHP has support for a few job queues, but I have used Gearman in the past and I have written a custom wrapper around the Linux at command. Both of these could be used to achieve "thread-like" behaviour without recompiling PHP.

Treffynnon
  • 21,365
  • 6
  • 65
  • 98