Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pthreads vs Parallel for infinite loops on PHP

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?

like image 254
brb Avatar asked Jun 04 '19 08:06

brb


People also ask

Does PHP allow multithreading?

PHP applications, undoubtedly work effectively with multithreading capabilities. Multithreading is something similar to multitasking, but it enables to process multiple jobs at one time, rather than on multiple processes.

Are there threads in PHP?

PHP applications can create, read, write, execute and synchronize with Threads, Workers and Threaded objects. This extension is considered unmaintained and dead. Consider using parallel instead. The pthreads extension cannot be used in a web server environment.


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 ...

like image 80
Joe Watkins Avatar answered Sep 18 '22 02:09

Joe Watkins