Advertisement
Guest User

cond.php

a guest
Jan 11th, 2014
29
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.20 KB | None | 0 0
  1. <?php
  2. define("SECOND", 1000000);
  3.  
  4. function trace( $sender, $msg )
  5. {
  6.     $ts = microtime( true );
  7.     echo date( 'd/m H:i:s', $ts ),
  8.          substr( sprintf( "%.6f", $ts - (int) $ts ), 1 ),
  9.           ' ',
  10.           $sender, ': ', $msg, "\n";
  11. }
  12.  
  13. class Test extends Thread
  14. {  
  15.     public $stopped;
  16.    
  17.     public function __construct($mutex, $cond) {
  18.         $this->mutex = $mutex;
  19.         $this->cond = $cond;
  20.     }
  21.    
  22.     public function run()
  23.     {
  24.         while(true) {
  25.             Mutex::lock($this->mutex);
  26.             if (!$this->stopped) {
  27.                 trace(Thread::getThreadId(), "running" );
  28.                 if( @Cond::wait( $this->cond, $this->mutex, 5 * SECOND) ) {
  29.                     if ($this->stopped) {
  30.                         break;
  31.                     }
  32.                 }  
  33.             } else break;
  34.             Mutex::unlock($this->mutex);
  35.         }
  36.        
  37.         Mutex::unlock($this->mutex);
  38.        
  39.         trace(Thread::getThreadId(), "leaving");
  40.     }
  41.    
  42.     public function stop()
  43.     {
  44.         trace(Thread::getThreadId(), "stopping");
  45.    
  46.         $this->stopped = true;
  47.    
  48.         Mutex::lock($this->mutex);
  49.         Cond::signal($this->cond);
  50.         Mutex::unlock($this->mutex);
  51.        
  52.         $this->join();
  53.     }
  54. }
  55.  
  56. $mutex = Mutex::create();
  57. $cond = Cond::create();
  58.  
  59. $test = new Test($mutex, $cond);
  60. $test->start();
  61. usleep( 5 * SECOND );
  62. $test->stop();
  63.  
  64. Mutex::destroy($mutex);
  65. Cond::destroy($cond);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement