I'm trying to implement multi_threading program with php, I've downloaded pthread package and did all of the required configuration. and then I tried to run this code:
<?php
class AsyncOperation extends Thread {
public function __construct($arg) {
$this->arg = $arg;
}
public function run() {
if ($this->arg) {
$sleep = mt_rand(1, 10);
printf('%s: %s -start -sleeps %d' . "\n", date("g:i:sa"), $this->arg, $sleep);
sleep($sleep);
printf('%s: %s -finish' . "\n", date("g:i:sa"), $this->arg);
}
}
}
// Create a array
$stack = array();
//Iniciate Miltiple Thread
foreach ( range("A", "D") as $i ) {
$stack[] = new AsyncOperation($i);
}
// Start The Threads
foreach ( $stack as $t ) {
$t->start();
}
?>
but every time I run the code I get something like that:
4:29:47pm: A -start -sleeps 1
4:29:48pm: A -finish
4:29:47pm: C -start -sleeps 3
4:29:50pm: C -finish
4:29:47pm: D -start -sleeps 4
4:29:51pm: D -finish
4:29:47pm: B -start -sleeps 7
4:29:54pm: B -finish
another run:
5:29:21pm: A -start -sleeps 1
5:29:22pm: A -finish
5:29:21pm: B -start -sleeps 3
5:29:24pm: B -finish
5:29:21pm: D -start -sleeps 8
5:29:29pm: D -finish
5:29:21pm: C -start -sleeps 9 5:29:30pm: C -finish
as you can see, the problem that it seems that threads are not working at the same time, whenever thread is start, no other thread starts before its done. the intrested thing that i noticed is that the threads are always ordered starting from the smallest sleep time!
I expect some run like this:
12:00:06pm: A -start -sleeps 5
12:00:06pm: B -start -sleeps 3
12:00:06pm: C -start -sleeps 10
12:00:06pm: D -start -sleeps 2
12:00:08pm: D -finish
12:00:09pm: B -finish
12:00:11pm: A -finish
12:00:16pm: C -finish
could some one tell me how can I get the wanted run? I'm using php5. note: I got the code from other post in this website: check it up
many thanks in advance.