PHP多線程實現有界阻塞隊列

PHP-Pthreads實現有界阻塞隊列

##知識點git

  • 基本Pthreads運行環境
  • PHP線程之間通訊與怎麼合理的操做一組公共數據(線程沒法操做一組公共數據,那麼線程將毫無用處)
  • PHP線程雖然是基於TSRM實現,但不表明不須要考慮線程安全。
  • 分享一篇好文章https://gist.github.com/krakjoe/6437782
class myQueue extends Threaded {
	public function __construct($size){
		$this->atomic = 0;
		$this->minSize = 0;
		$this->maxSize = $size;
		$this->Queue = new Threaded();
	}
	public function put($item)  {
		$this->synchronized(function($thread,$item){
			while ($thread->Queue->count() == $thread->maxSize) {
					print "wait.."."\r\n";
					$this->wait();
			}
		    $thread->Queue[] = $item;
			print "[#myQueueArray] <"."添加元素".$item."\r\n";
			$thread->increment();
			$thread->notify();
		}, $this,$item);
	}
	public function tack()      {
		$item = null; 
		$this->synchronized(function($thread,$item){
			while ($thread->Queue->count() == $thread->minSize) {
				print "wait.."."\r\n";
				$this->wait();
			}

			$item = $thread->Queue->shift();
			print "[#myQueueArray] >"."移除元素".$item."\r\n";
			$thread->decrement();
			$thread->notify();
		}, $this,$item);
		return $item;
	}
	public function increment() { $this->automic += 1; }
	public function decrement() { $this->automic -= 1;}
	public function run(){
		/* this particular object won't run */
	}
}

$myQueue = new myQueue(5);
$myQueue->put('a');
$myQueue->put('b');
$myQueue->put('c');
$myQueue->put('d');
$myQueue->put('e');

$name = 't1'; 
$t1 = new class($myQueue,$name) extends Thread {
	public function __construct(Threaded $myQueue,$name) {
		$this->name = $name;
		$this->myQueue = $myQueue;
	}
	public function run() {
	     $this->myQueue->put('f');
	     $this->myQueue->put('g');
	}
};
$t1->start();
$name = 't2'; 
$t2 = new class($myQueue,$name) extends Thread {
	public function __construct(Threaded $myQueue,$name) {
		$this->name = $name;
		$this->myQueue = $myQueue;
	}
	public function run() {
	     $this->myQueue->tack();
	     $this->myQueue->tack();

	}
};
$t2->start();

###運行結果github

相關文章
相關標籤/搜索