I am trying to learn multithreading with PHP. I've installed PHP 7.2.14
with ZTS support, and looked over a lot of examples on the net, and afterwards, tried to create a simple script, to see if I understand the things that I've learned. The problem is, that it seems, I don't:)
Here's the script I've made:
class Task extends Threaded
{
private $workToBeDone;
public $DataHolder;
public function __construct($i, $z, $DataHolder)
{
$this->workToBeDone = array($i, $z);
$this->DataHolder = $DataHolder;
}
public function run()
{
$results = 0;
for ($i=$this->workToBeDone[0]; $i<=$this->workToBeDone[1]; $i++) {
$results++;
}
$this->synchronized(function ($DataHolder) use($results) {
echo $results . "\n";
$DataHolder->counter+=$results;
}, $this->DataHolder);
}
}
class MyDataHolder {
public $counter;
}
$DataHolder = new MyDataHolder;
$pool = new Pool(4);
$tasks = array();
for ($i = 0; $i < 15; ++$i) {
$Task = new Task(1,100, $DataHolder);
$pool->submit($Task);
}
while ($pool->collect());
$pool->shutdown();
echo "Total: " . $DataHolder->counter;
This script, should create 15 separate tasks, and in each task I would have to iterate a 100 times. After each 100 iterations are ready, I would like to store the number of times I've iterated in the MyDataHolder
class, to be able to access it later.
The expected behaviour would be, that when I run this script, I would like to see 100
printed out 15 times on the screen, and in the end, I would like to see Total: 1500
printed out.
Instead of this, 100
is printed out 15 times, but the total value remains empty at the end.
What am I doing wrong? How can I collect the data from each of my threads, to use it later on in the program?