Multithreading Extensions in PHP

Learn about extensions for multithreading available in PHP with coding examples.

The pthreads extension

Developed by Joe Watkins, the pthreads extension is a facsimile of the thread model on POSIX systems that are mostly compatible with the C programming language. Although pthreads is primarily OO-focussed, its utilities allow for the usage of functional programming ideas. Also worth noting about pthreads is the thread model it conforms to, that is, thread pooling.

A thread pool is akin to a typical boss-worker system with one boss and multiple workers. A boss (the main thread) dispatches workers to do useful work usually expressed in arbitrary thread functions. Regardless of the nature of an isolated (siloed) function, it should synchronize with the other threads in its pool and share process resources which are ever so finite in a coordinated manner. Not to worry, though, as pthreads guarantees the synchronization of all threads.

The task

Out of the realm of real-world application development, it’s hard to fathom the applicability of threading with functions with resource usage that’s plentiful enough to warrant thread siloing. A non-trampoline-optimized thread function that outputs a sequence of Fibonnaci numbers should suffice for demonstration purposes.

Get hands-on with 1200+ tech skills courses.