12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- <?php
- abstract class CoPool
- {
- private $mMaxClient;
- private $mFreeClients;
- private $mUsingCount;
- private $mSuspendCIDS;
- private $mStop;
- public function __construct($max_clients)
- {
- $this->mMaxClient = $max_clients;
- $this->mUsingCount = 0;
- $this->mFreeClients = [];
- $this->mSuspendCIDS = [];
- $this->mStop = false;
- }
- public function get($args)
- {
- if(!empty($this->mFreeClients)) {
- $client = $this->mFreeClients[0];
- unset($this->mFreeClients[0]);
- $this->mFreeClients = array_values($this->mFreeClients);
- }
- elseif($this->mUsingCount < $this->mMaxClient) {
- $client = $this->create_client($args);
- }
- else {
- $this->mSuspendCIDS[] = Co::getCid();
- Co::suspend();
- $client = $this->mFreeClients[0];
- unset($this->mFreeClients[0]);
- $this->mFreeClients = array_values($this->mFreeClients);
- }
- $this->mUsingCount++;
- Log::record("redis get mUsingCount={$this->mUsingCount}",Log::DEBUG);
- return $client;
- }
- public function put($client) {
- $this->mFreeClients[] = $client;
- $this->mUsingCount--;
- $cid = $this->getSuspend();
- if($cid > 0) {
- Co::resume($cid);
- }
- $count = count($this->mFreeClients);
- $waitings = count($this->mSuspendCIDS);
- Log::record("redis resume cid={$cid} mUsingCount={$this->mUsingCount} frees={$count} waitings={$waitings}",Log::DEBUG);
- }
- private function getSuspend()
- {
- if(empty($this->mSuspendCIDS)) {
- return 0;
- }
- else {
- $cid = $this->mSuspendCIDS[0];
- unset($this->mSuspendCIDS[0]);
- $this->mSuspendCIDS = array_values($this->mSuspendCIDS);
- return $cid;
- }
- }
- public function stoped() {
- return $this->mStop;
- }
- public function stop() {
- $this->mStop = true;
- }
- abstract public function create_client($args);
- }
|