CoPool.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 = array_shift($this->mFreeClients);
  21. }
  22. elseif($this->mUsingCount < $this->mMaxClient) {
  23. $client = $this->create_client($args);
  24. }
  25. else {
  26. $this->mSuspendCIDS[] = Co::getCid();
  27. Co::suspend();
  28. $client = array_shift($this->mFreeClients);
  29. }
  30. $this->mUsingCount++;
  31. return $client;
  32. }
  33. public function put($client) {
  34. $this->mFreeClients[] = $client;
  35. $this->mUsingCount--;
  36. $cid = $this->getSuspend();
  37. if($cid > 0) {
  38. Co::resume($cid);
  39. }
  40. }
  41. private function getSuspend()
  42. {
  43. if(empty($this->mSuspendCIDS)) {
  44. return 0;
  45. }
  46. else {
  47. $cid = array_shift($this->mSuspendCIDS);
  48. return $cid;
  49. }
  50. }
  51. public function stoped() {
  52. return $this->mStop;
  53. }
  54. public function stop() {
  55. $this->mStop = true;
  56. }
  57. abstract public function create_client($args);
  58. }