php 多线程队列,PHP多线程实现有界阻塞队列

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();

###运行结果

285244acfde8ff37de3ca360ce8d589e.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值