|
@@ -0,0 +1,82 @@
|
|
|
+<?php
|
|
|
+
|
|
|
+abstract class CoRefPool
|
|
|
+{
|
|
|
+ private $mMaxClient;
|
|
|
+ private $mFreeClients;
|
|
|
+ private $mUsingClients;
|
|
|
+ private $mSuspendCIDS;
|
|
|
+ private $mStop;
|
|
|
+
|
|
|
+ public function __construct($max_clients)
|
|
|
+ {
|
|
|
+ $this->mMaxClient = $max_clients;
|
|
|
+ $this->mUsingClients = [];
|
|
|
+ $this->mFreeClients = [];
|
|
|
+ $this->mSuspendCIDS = [];
|
|
|
+ $this->mStop = false;
|
|
|
+ }
|
|
|
+
|
|
|
+ public function get($cid)
|
|
|
+ {
|
|
|
+ if(array_key_exists($cid,$this->mUsingClients)) {
|
|
|
+ $this->mUsingClients[$cid]['ref_count'] += 1;
|
|
|
+ return $this->mUsingClients[$cid]['object'];
|
|
|
+ }
|
|
|
+
|
|
|
+ if(!empty($this->mFreeClients)) {
|
|
|
+ $client = $this->mFreeClients[0];
|
|
|
+ unset($this->mFreeClients[0]);
|
|
|
+ $this->mFreeClients = array_values($this->mFreeClients);
|
|
|
+ $this->mUsingClients[$cid] = ['object' =>$client,'ref_count' => 1];
|
|
|
+ }
|
|
|
+ elseif(count($this->mUsingClients) < $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("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("put 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);
|
|
|
+}
|