Pthreads vs Parallel for infinite loops on PHP

Viewed 2577

I was looking for a way to perform multi-threads on PHP and came across the pthreads PHP API, which I think could be easy to implement (however I'll have to find out how to install the PHP version with ZTS support for Debian).

The thing is that when I was looking at the pthreads php.net documentation I found this:

Tip Consider using parallel instead.

Which I didn't know about.

My goal is to get a list of items and for each one, open a websocket that listens for certain updates forever. So the thread should be there forever and if killed, or stopped, or so, it should be restarted (however I think I can handle this externally).

I'm not sure which one would be the most appropriate for this situation. Any recommendation?

1 Answers

The first thing to say is that there is nothing in the description of your application that demands the use of threads, it would seem what you really want is asynchronous concurrency: Asynchronous concurrency is typically used to increase the throughput of I/O bound code, by eliminating unnecessary waiting. Parallel concurrency is typically used to increase the throughput of CPU bound code, by utilising more cores.

There are a few good frameworks for implementing non-blocking I/O in PHP, the one I would recommend is amphp.

Of course, I may not have a full description of your application, so onto the subject of pthreads: It is made obsolete by parallel, new projects should use parallel.

Disclaimer: I wrote pthreads and parallel ...

Related