当前位置:Gxlcms > PHP教程 > php多任务程序实例解析

php多任务程序实例解析

时间:2021-07-01 10:21:17 帮助过:7人阅读

本文以实例简单解析了php多任务程序的实现方法,具体代码如下:

  1. <?php
  2. error_reporting(E_ALL);
  3. set_time_limit(0);
  4. /**
  5. * php多任务程序的实现
  6. * 借助proc_open
  7. * 其实该叫进程(process)
  8. * 能启动多进程,你可以使用你的想象力做你想做的了,以后再写个能用的
  9. * 如果你是在linux上跑php,并且启用pcntl模块后,使用pcntl函数该更好
  10. *
  11. */
  12. class Thread {
  13. protected $_pref; // process reference
  14. protected static $_instance = null;
  15. protected $_pipes;
  16. private function __construct() {
  17. $this->_pref = 0;
  18. }
  19. public static function getInstance($file) {
  20. if (null == self::$_instance) {
  21. self::$_instance = new self;
  22. }
  23. $descriptor = array(
  24. 0 => array("pipe", "r"),
  25. 1 => array("pipe", "w"),
  26. 2 => array("file", "./error-output.txt", "a"),
  27. );
  28. self::$_instance->_pref = proc_open("php -q $file", $descriptor, self::$_instance->_pipes);
  29. return true;
  30. }
  31. public function __destruct() {
  32. proc_close($this->_pref);
  33. $this->_pref = null;
  34. }
  35. }
  36. // 测试代码
  37. $file = __FILE__;
  38. if(empty($argv[1])) {
  39. $t2 = Thread::getInstance("$file 1");
  40. $t3 = Thread::getInstance("$file 2");
  41. $t4 = Thread::getInstance("$file 3");
  42. $t5 = Thread::getInstance("$file 4");
  43. $t5 = Thread::getInstance("$file 5");
  44. $t5 = Thread::getInstance("$file 6");
  45. $t2 = Thread::getInstance("$file 7");
  46. $t3 = Thread::getInstance("$file 8");
  47. $t4 = Thread::getInstance("$file 9");
  48. $t5 = Thread::getInstance("$file 10");
  49. $t5 = Thread::getInstance("$file 11");
  50. $t5 = Thread::getInstance("$file 12");
  51. echo "Main thread done\n";
  52. } else {
  53. $somecontent = "\r\n//~~~~~~~~~~~~-这次请求序号是:" . $argv[1];
  54. sleep(mt_rand(0, 3));
  55. $handle = fopen($file, 'a+');
  56. fwrite($handle, $somecontent);
  57. }

人气教程排行