CoPool.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. abstract class CoPool
  3. {
  4. private $mMaxClient;
  5. private $mFreeClients;
  6. private $mUsingCount;
  7. private $mSuspendCIDS;
  8. private $mStop;
  9. public function __construct($max_clients)
  10. {
  11. $this->mMaxClient = $max_clients;
  12. $this->mUsingCount = 0;
  13. $this->mFreeClients = [];
  14. $this->mSuspendCIDS = [];
  15. $this->mStop = false;
  16. }
  17. public function get($args)
  18. {
  19. if(!empty($this->mFreeClients)) {
  20. $client = $this->mFreeClients[0];
  21. unset($this->mFreeClients[0]);
  22. $this->mFreeClients = array_values($this->mFreeClients);
  23. }
  24. elseif($this->mUsingCount < $this->mMaxClient) {
  25. $client = $this->create_client($args);
  26. }
  27. else {
  28. $this->mSuspendCIDS[] = Co::getCid();
  29. Co::suspend();
  30. $client = $this->mFreeClients[0];
  31. unset($this->mFreeClients[0]);
  32. $this->mFreeClients = array_values($this->mFreeClients);
  33. }
  34. $this->mUsingCount++;
  35. Log::record("redis get mUsingCount={$this->mUsingCount}",Log::DEBUG);
  36. return $client;
  37. }
  38. public function put($client) {
  39. $this->mFreeClients[] = $client;
  40. $this->mUsingCount--;
  41. $cid = $this->getSuspend();
  42. if($cid > 0) {
  43. Co::resume($cid);
  44. }
  45. $count = count($this->mFreeClients);
  46. $waitings = count($this->mSuspendCIDS);
  47. Log::record("redis resume cid={$cid} mUsingCount={$this->mUsingCount} frees={$count} waitings={$waitings}",Log::DEBUG);
  48. }
  49. private function getSuspend()
  50. {
  51. if(empty($this->mSuspendCIDS)) {
  52. return 0;
  53. }
  54. else {
  55. $cid = $this->mSuspendCIDS[0];
  56. unset($this->mSuspendCIDS[0]);
  57. $this->mSuspendCIDS = array_values($this->mSuspendCIDS);
  58. return $cid;
  59. }
  60. }
  61. public function stoped() {
  62. return $this->mStop;
  63. }
  64. public function stop() {
  65. $this->mStop = true;
  66. }
  67. abstract public function create_client($args);
  68. }