Php: when to use pthread Php: when to use pthread multithreading multithreading

Php: when to use pthread


There are many examples included in the distribution and available on github:

https://github.com/krakjoe/pthreads/tree/master/examples

These examples include such things as a general purpose thread pool, a multi-threaded socket server and an SQLWorker.

The Threads pthreads creates are as sane, and as safe, as the threads that Zend itself sets up to service requests via a multi-threaded SAPI. They are compatible with all the same functionality, plus all you expect from a high level threading API (nearly).

There will always be limitations to implementing threading deep in the bowels of a shared nothing architecture, but the benefits, in terms of using better the physical resources at your disposal, but also the overall usability of PHP for any given task far outweigh the overhead of working around that environment.

The objects included in pthreads work as any other PHP object does, you can read, write and execute their methods, from any context with a reference to the object.

You are thinking exactly along the right lines: a measure of efficiency is not in the number of threads your application executes but how those threads are utilized to best serve the primary purpose of the application. Workers are a good idea, wherever you can use them, do so.

With regard to the specific things you asked about, a LoggingWorker is a good idea and will work, do not attempt to share that stream as there is no point, it will be perfectly stable if the Worker opens the log file, or database connection and stackables executed by it can access them. An SQLWorker is included in the examples, again, another good idea where the API lacks a decent async API, or you just get to prefer the flow of multi-threaded programming.

You won't get a better, or more correct answer: I wrote pthreads, on my own.