Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- define("SECOND", 1000000);
- function trace( $sender, $msg )
- {
- $ts = microtime( true );
- echo date( 'd/m H:i:s', $ts ),
- substr( sprintf( "%.6f", $ts - (int) $ts ), 1 ),
- ' ',
- $sender, ': ', $msg, "\n";
- }
- class Test extends Thread
- {
- public $stopped;
- public function __construct($mutex, $cond) {
- $this->mutex = $mutex;
- $this->cond = $cond;
- }
- public function run()
- {
- while(true) {
- Mutex::lock($this->mutex);
- if (!$this->stopped) {
- trace(Thread::getThreadId(), "running" );
- if( @Cond::wait( $this->cond, $this->mutex, 5 * SECOND) ) {
- if ($this->stopped) {
- break;
- }
- }
- } else break;
- Mutex::unlock($this->mutex);
- }
- Mutex::unlock($this->mutex);
- trace(Thread::getThreadId(), "leaving");
- }
- public function stop()
- {
- trace(Thread::getThreadId(), "stopping");
- $this->stopped = true;
- Mutex::lock($this->mutex);
- Cond::signal($this->cond);
- Mutex::unlock($this->mutex);
- $this->join();
- }
- }
- $mutex = Mutex::create();
- $cond = Cond::create();
- $test = new Test($mutex, $cond);
- $test->start();
- usleep( 5 * SECOND );
- $test->stop();
- Mutex::destroy($mutex);
- Cond::destroy($cond);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement