I currently have the code seen here:
<?php
class workerThread extends Thread {
public function __construct($i) {
$this->i = $i;
}
public function run() {
echo $this->i . " ";
sleep(1);
echo $this->i . " ";
}
}
for ($i=1; $i<=5; $i++) {
$workers[$i]= new workerThread($i);
$workers[$i]->start();
}
?>
What I would expect this to do would be to echo 1 2 3 4 5
, wait 1 second, and then echo 1 2 3 4 5
. However, instead it waits for the entire program to finish and then spits out 1 1 2 2 3 3 4 4 5 5
. For some reason it is not behaving asynchronously. What am I doing wrong?
Edit: Does the same thing using usleep(1000000)
instead of sleep(1)
This is a copy-paste from PHP API Reference:
After the run method is executed the Thread will exit immediately, it will be joined with the creating Thread at the appropriate time.
I assume, the engine belives the appropriate time to join those threads is upon next loop iteration.