The answer to the question is the use of the Pool and Worker abstractions.
The basic idea is that you ::submit Threaded objects to the Pool , which it adds to the next available Worker , distributing your Threaded objects (circular) across all Workers .
The following is super simple code for PHP7 (pthreads v3):
<?php $jobs = []; while (count($jobs) < 2000) { $jobs[] = mt_rand(0, 1999); } $pool = new Pool(8); foreach ($jobs as $job) { $pool->submit(new class($job) extends Threaded { public function __construct(int $job) { $this->job = $job; } public function run() { var_dump($this->job); } }); } $pool->shutdown(); ?>
The work is useless, obviously. In the real world, I think your $jobs array continues to grow, so you can just swap foreach for some do {} while and continue to call ::submit for new jobs.
In the real world, you'll want to collect garbage in the same loop (just call Pool::collect with no parameters for the default behavior).
It is noteworthy that none of this would be possible if it really were that PHP was not intended to work in multi-threaded environments ... it is definitely .
This is the answer to the question, but it does not make it the best solution to your problem.
You mentioned in the comments that you assume that 8 threads running Symfony code take up less memory than 8 processes. This is not the case, PHP does not share anything all the time. You can expect that 8 Symfony threads take up as much memory as 8 Symfony processes, in fact, a bit more. The advantage of using threads over processes is that they can communicate, synchronize and (communicate) with each other.
Just because you can does not mean what you need. The best solution for this task is probably to use a ready-made package or software designed to perform the necessary actions.
Learning this material is good enough to implement a reliable solution - it will take a long time and you wonβt want to deploy this first solution ...
If you decide to ignore my advice and let it go, you can find many examples in the github repository for pthreads.