Worker Pools in PHP
Our example demonstrates how to implement a worker pool using PHP’s multi-threading capabilities. We’ll use the pthreads extension, which allows for true parallel execution in PHP.
First, let’s define our worker class:
Now, let’s implement our main script:
In this example, we create a Worker
class that extends the Thread
class provided by pthreads. Each worker runs in its own thread and processes jobs from a shared job queue.
In the main script, we:
- Create a pool of jobs.
- Start three worker threads.
- Wait for all workers to finish.
- Print the results.
To run this program, you need to have the pthreads extension installed and enabled in your PHP environment. Save the code in a file named worker_pools.php
and run it using:
The program demonstrates concurrent execution of jobs by multiple workers. Despite having 5 seconds of total work (5 jobs, each taking 1 second), the program completes in about 2 seconds because the work is distributed among 3 workers running concurrently.
Note that PHP’s threading model with pthreads is different from some other languages. It’s important to properly manage shared resources and be aware of potential issues like race conditions when working with threads in PHP.