Threads

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->availableFALSE;
      
Thread::notify();
      return 
$this->value;
    }
    
    
public function put($value) {
      while (
$this->available) {
        
Thread::wait();
      }
      
$this->value$value;
      
$this->availableTRUE;
      
Thread::notify();
    }
    
    
public function getInstance() {
      static 
$i0;
      
      if (!
self::$instanceself::$instance= new Resource($i++);
      return 
self::$instance;
    }
  }
  
  class 
Consumer extends Thread {
    
public
      $resource  
NULL;
    
    
private
      $i         
0;
    
    
public function __construct() {
      
$this->resourceResource::getInstance();
    }
    
    
public function run() {
      for (
$this->i0$this->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->resourceResource::getInstance();
    }
    
    
public function run() {
      for (
$this->i0$this->10$this->i++) {
        
$this->resource->put($this->i);
        
printf(">>> Producer put %d into resource #%d\n"$this->i$this->resource->id);
        
        
usleep(500000 rand(02));
      }
    }
  }
  
  
$p= new Producer();
  
$p->start();
  
$c= new Consumer();
  
$c->start();
  
  
sleep(10);
  
printf("### Done\n");
?>