PHP-Pthreads实现有界阻塞队列
##知识点
基本Pthreads运行环境
PHP线程之间通信与怎么合理的操作一组公共数据(线程无法操作一组公共数据,那么线程将毫无用处)
PHP线程虽然是基于TSRM实现,但不代表不需要考虑线程安全。
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]
$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();
###运行结果