consumer_producer.php
<?php
class Resource {
private
$value = NULL,
$available = FALSE;
public
$id = 0;
private static
$instance = NULL;
private function __construct($id) {
$this->id= $id;
}
public function get() {
while (!$this->available) {
Thread::wait();
}
$this->available= FALSE;
Thread::notify();
return $this->value;
}
public function put($value) {
while ($this->available) {
Thread::wait();
}
$this->value= $value;
$this->available= TRUE;
Thread::notify();
}
public function getInstance() {
static $i= 0;
if (!self::$instance) self::$instance= new Resource($i++);
return self::$instance;
}
}
class Consumer extends Thread {
public
$resource = NULL;
private
$i = 0;
public function __construct() {
$this->resource= Resource::getInstance();
}
public function run() {
for ($this->i= 0; $this->i < 10; $this->i++) {
$val= $this->resource->get();
printf("<<< Consumer got %d from resource #%d\n", $val, $this->resource->id);
}
}
}
class Producer extends Thread {
public
$resource = NULL;
private
$i = 0;
public function __construct() {
$this->resource= Resource::getInstance();
}
public function run() {
for ($this->i= 0; $this->i < 10; $this->i++) {
$this->resource->put($this->i);
printf(">>> Producer put %d into resource #%d\n", $this->i, $this->resource->id);
usleep(500000 * rand(0, 2));
}
}
}
$p= new Producer();
$p->start();
$c= new Consumer();
$c->start();
sleep(10);
printf("### Done\n");
?>