Sharing arrays between threads has locking problems
PHP 7.0.4 Pthreads: Current build (3.1.7dev) OS: Ubuntu/14.04 LTS (HVM) Machine1: AWS EC2 t2.micro (single CPU 1GB memory) Machine2: AWD EC2 c4.xlarge (4 CPU 7.5GB memory) Machine3: Local VM in Virtual Box (1 CPU 1GB Memory)
I think there might be a problem with shared arrays and locking when things get 'busy'.
I can replicate it with your example, 'StackableArray.php'. I modified it to add 10000 elements per thread to load it up to make it happen consistently, and to report on the total added elements at the end to show loss.
<?php
$hammers = 500;
class StackableArray extends Threaded {
public function run() {}
}
class T extends Thread {
public function __construct($test){
$this->test = $test;
$this->start();
}
public function run(){
for ($x=0;$x<10000;$x++) {
$this->test[]=rand(0, 10);
}
}
}
$s = new StackableArray();
$ts = array();
while(@$i++ < $hammers){
$ts[]=new T($s);
}
printf("GOT %d T's\n", count($ts));
foreach($ts as $t)
$t->join();
printf("GOT %d S's\n", count($s));
?>
On a single CPU machine, it seems that $s is missing around ~15 elements out of 5000000.
Its much worse on a multicpu machine, 4 CPUs, and it only manages to add around 3.3 million of the elements.
If you drop it down to 10 threads just to prove it isn't anything to do with the high threads amount, the single CPU machine only drops 1 per 100000, but the multicpu drops around 30000 out of 100000.
Also tried it locally on a VM, and similar problems occurred.
If you 'synchronized' around the array add, then it fixes it and non are dropped, so I can only presume that the internal locking is not working quite correctly here?
I could do the synch thing, but I'm guessing there is an overhead with that as there will be 2 locks effectively, or are you doing any clever lock 'saving' inside synch blocks, because the lock would already be there from the synch, so theoretically you could skip the internal one?
Some more testing, it seems to be the [] that is causing the problem.
If you add into the array with specific keys, then it never misses one.
For example:
$this->test[self::$threadID.'|'.$x]=rand(0, 10);
And pass in a unique threadID (ie $i) to each thread in the while loop.
I havent seen it drop any in this instance, its just when using [].
Well spotted ... thanks :)
The fix for this broke CI ... reviewing ...
Tested and works fine for me now, thanks for the quick fix Joe.