Select.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. <?php
  2. /**
  3. * This file is part of workerman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. namespace Workerman\Events;
  15. use Throwable;
  16. use Workerman\Worker;
  17. /**
  18. * select eventloop
  19. */
  20. class Select implements EventInterface
  21. {
  22. /**
  23. * All listeners for read/write event.
  24. *
  25. * @var array
  26. */
  27. protected $readEvents = [];
  28. /**
  29. * All listeners for read/write event.
  30. *
  31. * @var array
  32. */
  33. protected $writeEvents = [];
  34. /**
  35. * @var array
  36. */
  37. protected $exceptEvents = [];
  38. /**
  39. * Event listeners of signal.
  40. *
  41. * @var array
  42. */
  43. protected $signalEvents = [];
  44. /**
  45. * Fds waiting for read event.
  46. *
  47. * @var array
  48. */
  49. protected $readFds = [];
  50. /**
  51. * Fds waiting for write event.
  52. *
  53. * @var array
  54. */
  55. protected $writeFds = [];
  56. /**
  57. * Fds waiting for except event.
  58. *
  59. * @var array
  60. */
  61. protected $exceptFds = [];
  62. /**
  63. * Timer scheduler.
  64. * {['data':timer_id, 'priority':run_timestamp], ..}
  65. *
  66. * @var \SplPriorityQueue
  67. */
  68. protected $scheduler = null;
  69. /**
  70. * All timer event listeners.
  71. * [[func, args, flag, timer_interval], ..]
  72. *
  73. * @var array
  74. */
  75. protected $eventTimer = [];
  76. /**
  77. * Timer id.
  78. *
  79. * @var int
  80. */
  81. protected $timerId = 1;
  82. /**
  83. * Select timeout.
  84. *
  85. * @var int
  86. */
  87. protected $selectTimeout = 100000000;
  88. /**
  89. * Construct.
  90. */
  91. public function __construct()
  92. {
  93. // Init SplPriorityQueue.
  94. $this->scheduler = new \SplPriorityQueue();
  95. $this->scheduler->setExtractFlags(\SplPriorityQueue::EXTR_BOTH);
  96. }
  97. /**
  98. * {@inheritdoc}
  99. */
  100. public function delay(float $delay, $func, $args)
  101. {
  102. $timerId = $this->timerId++;
  103. $runTime = \microtime(true) + $delay;
  104. $this->scheduler->insert($timerId, -$runTime);
  105. $this->eventTimer[$timerId] = [$func, (array)$args];
  106. $selectTimeout = ($runTime - \microtime(true)) * 1000000;
  107. $selectTimeout = $selectTimeout <= 0 ? 1 : (int)$selectTimeout;
  108. if ($this->selectTimeout > $selectTimeout) {
  109. $this->selectTimeout = $selectTimeout;
  110. }
  111. return $timerId;
  112. }
  113. /**
  114. * {@inheritdoc}
  115. */
  116. public function repeat(float $delay, $func, $args)
  117. {
  118. $timerId = $this->timerId++;
  119. $runTime = \microtime(true) + $delay;
  120. $this->scheduler->insert($timerId, -$runTime);
  121. $this->eventTimer[$timerId] = [$func, (array)$args, $delay];
  122. $selectTimeout = ($runTime - \microtime(true)) * 1000000;
  123. $selectTimeout = $selectTimeout <= 0 ? 1 : (int)$selectTimeout;
  124. if ($this->selectTimeout > $selectTimeout) {
  125. $this->selectTimeout = $selectTimeout;
  126. }
  127. return $timerId;
  128. }
  129. /**
  130. * {@inheritdoc}
  131. */
  132. public function offDelay($timerId)
  133. {
  134. if (isset($this->eventTimer[$timerId])) {
  135. unset($this->eventTimer[$timerId]);
  136. return true;
  137. }
  138. return false;
  139. }
  140. /**
  141. * {@inheritdoc}
  142. */
  143. public function offRepeat($timerId)
  144. {
  145. return $this->offDelay($timerId);
  146. }
  147. /**
  148. * {@inheritdoc}
  149. */
  150. public function onReadable($stream, $func)
  151. {
  152. $count = \count($this->readFds);
  153. if ($count >= 1024) {
  154. echo "Warning: system call select exceeded the maximum number of connections 1024, please install event/libevent extension for more connections.\n";
  155. } else if (\DIRECTORY_SEPARATOR !== '/' && $count >= 256) {
  156. echo "Warning: system call select exceeded the maximum number of connections 256.\n";
  157. }
  158. $fdKey = (int)$stream;
  159. $this->readEvents[$fdKey] = $func;
  160. $this->readFds[$fdKey] = $stream;
  161. }
  162. /**
  163. * {@inheritdoc}
  164. */
  165. public function offReadable($stream)
  166. {
  167. $fdKey = (int)$stream;
  168. unset($this->readEvents[$fdKey], $this->readFds[$fdKey]);
  169. }
  170. /**
  171. * {@inheritdoc}
  172. */
  173. public function onWritable($stream, $func)
  174. {
  175. $count = \count($this->writeFds);
  176. if ($count >= 1024) {
  177. echo "Warning: system call select exceeded the maximum number of connections 1024, please install event/libevent extension for more connections.\n";
  178. } else if (\DIRECTORY_SEPARATOR !== '/' && $count >= 256) {
  179. echo "Warning: system call select exceeded the maximum number of connections 256.\n";
  180. }
  181. $fdKey = (int)$stream;
  182. $this->writeEvents[$fdKey] = $func;
  183. $this->writeFds[$fdKey] = $stream;
  184. }
  185. /**
  186. * {@inheritdoc}
  187. */
  188. public function offWritable($stream)
  189. {
  190. $fdKey = (int)$stream;
  191. unset($this->writeEvents[$fdKey], $this->writeFds[$fdKey]);
  192. }
  193. /**
  194. * {@inheritdoc}
  195. */
  196. public function onExcept($stream, $func)
  197. {
  198. $fdKey = (int)$stream;
  199. $this->exceptEvents[$fdKey] = $func;
  200. $this->exceptFds[$fdKey] = $stream;
  201. }
  202. /**
  203. * {@inheritdoc}
  204. */
  205. public function offExcept($stream)
  206. {
  207. $fdKey = (int)$stream;
  208. unset($this->exceptEvents[$fdKey], $this->exceptFds[$fdKey]);
  209. }
  210. /**
  211. * {@inheritdoc}
  212. */
  213. public function onSignal($signal, $func)
  214. {
  215. if (\DIRECTORY_SEPARATOR !== '/') {
  216. return null;
  217. }
  218. $this->signalEvents[$signal] = $func;
  219. \pcntl_signal($signal, [$this, 'signalHandler']);
  220. }
  221. /**
  222. * {@inheritdoc}
  223. */
  224. public function offsignal($signal)
  225. {
  226. unset($this->signalEvents[$signal]);
  227. \pcntl_signal($signal, SIG_IGN);
  228. }
  229. /**
  230. * Signal handler.
  231. *
  232. * @param int $signal
  233. */
  234. public function signalHandler($signal)
  235. {
  236. $this->signalEvents[$signal]($signal);
  237. }
  238. /**
  239. * Tick for timer.
  240. *
  241. * @return void
  242. */
  243. protected function tick()
  244. {
  245. $tasksToInsert = [];
  246. while (!$this->scheduler->isEmpty()) {
  247. $schedulerData = $this->scheduler->top();
  248. $timerId = $schedulerData['data'];
  249. $nextRunTime = -$schedulerData['priority'];
  250. $timeNow = \microtime(true);
  251. $this->selectTimeout = (int)(($nextRunTime - $timeNow) * 1000000);
  252. if ($this->selectTimeout <= 0) {
  253. $this->scheduler->extract();
  254. if (!isset($this->eventTimer[$timerId])) {
  255. continue;
  256. }
  257. // [func, args, timer_interval]
  258. $taskData = $this->eventTimer[$timerId];
  259. if (isset($taskData[2])) {
  260. $nextRunTime = $timeNow + $taskData[2];
  261. $tasksToInsert[] = [$timerId, -$nextRunTime];
  262. } else {
  263. unset($this->eventTimer[$timerId]);
  264. }
  265. try {
  266. $taskData[0](...$taskData[1]);
  267. } catch (Throwable $e) {
  268. Worker::stopAll(250, $e);
  269. }
  270. } else {
  271. break;
  272. }
  273. }
  274. foreach ($tasksToInsert as $item) {
  275. $this->scheduler->insert($item[0], $item[1]);
  276. }
  277. if (!$this->scheduler->isEmpty()) {
  278. $schedulerData = $this->scheduler->top();
  279. $nextRunTime = -$schedulerData['priority'];
  280. $timeNow = \microtime(true);
  281. $this->selectTimeout = \max((int)(($nextRunTime - $timeNow) * 1000000), 0);
  282. return;
  283. }
  284. $this->selectTimeout = 100000000;
  285. }
  286. /**
  287. * {@inheritdoc}
  288. */
  289. public function deleteAllTimer()
  290. {
  291. $this->scheduler = new \SplPriorityQueue();
  292. $this->scheduler->setExtractFlags(\SplPriorityQueue::EXTR_BOTH);
  293. $this->eventTimer = [];
  294. }
  295. /**
  296. * {@inheritdoc}
  297. */
  298. public function run()
  299. {
  300. while (1) {
  301. if (\DIRECTORY_SEPARATOR === '/') {
  302. // Calls signal handlers for pending signals
  303. \pcntl_signal_dispatch();
  304. }
  305. $read = $this->readFds;
  306. $write = $this->writeFds;
  307. $except = $this->exceptFds;
  308. if ($read || $write || $except) {
  309. // Waiting read/write/signal/timeout events.
  310. try {
  311. @stream_select($read, $write, $except, 0, $this->selectTimeout);
  312. } catch (Throwable $e) {
  313. }
  314. } else {
  315. $this->selectTimeout >= 1 && usleep($this->selectTimeout);
  316. }
  317. if (!$this->scheduler->isEmpty()) {
  318. $this->tick();
  319. }
  320. foreach ($read as $fd) {
  321. $fdKey = (int)$fd;
  322. if (isset($this->readEvents[$fdKey])) {
  323. $this->readEvents[$fdKey]($fd);
  324. }
  325. }
  326. foreach ($write as $fd) {
  327. $fdKey = (int)$fd;
  328. if (isset($this->writeEvents[$fdKey])) {
  329. $this->writeEvents[$fdKey]($fd);
  330. }
  331. }
  332. foreach ($except as $fd) {
  333. $fdKey = (int)$fd;
  334. if (isset($this->exceptEvents[$fdKey])) {
  335. $this->exceptEvents[$fdKey]($fd);
  336. }
  337. }
  338. }
  339. }
  340. /**
  341. * {@inheritdoc}
  342. */
  343. public function stop()
  344. {
  345. $this->deleteAllTimer();
  346. foreach ($this->signalEvents as $signal => $item) {
  347. $this->offsignal($signal);
  348. }
  349. $this->readFds = $this->writeFds = $this->exceptFds = $this->readEvents
  350. = $this->writeEvents = $this->exceptEvents = $this->signalEvents = [];
  351. }
  352. /**
  353. * {@inheritdoc}
  354. */
  355. public function getTimerCount()
  356. {
  357. return \count($this->eventTimer);
  358. }
  359. }