• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

单线程的编程语言php是如何实现多线程操作的

php 搞代码 3年前 (2022-01-22) 12次浏览 已收录 0个评论

大家都知道php这种语言本身只能是单线程的,一步操作运行完了执行下一步操作。

但有时候我们需要异步操作,多个线程同时运行,

下面我们来介绍php是如何实现多线程操作的

代码如下: 仅供参考

<?php/** * @title:        PHP多线程类(Thread) * @version:    1.0 * @author:        php.cn < [email protected] > * @published:    2010-11-2 *  * PHP多线程应用示例: *  require_once 'thread.class.php'; *  $thread = new thread(); *  $thread->addthread('action_log','a'); *  $thread->addthread('action_log','b'); *  $thread->addthread('action_log','c'); *  $thread->runthread(); *   *  function action_log($info) { *      $log = 'log/' . microtime() . '.log'; *      $txt = $info . "\r\n\r\n" . 'Set in ' . Date('h:i:s', time()) . (double)microtime() . "\r\n"; *      $fp = fopen($log, 'w'); *      fwrite($fp, $txt); *      fclose($fp); *  } */class thread {<span style="color:transparent">/本文来源gaodai#ma#com搞*!代#%^码网%</span><sub>搞代gaodaima码</sub>    var $hooks = array();    var $args = array();    function thread() {    }    function addthread($func)    {        $args = array_slice(func_get_args(), 1);        $this->hooks[] = $func;        $this->args[] = $args;        return true;    }    function runthread()    {        if(isset($_GET['flag']))        {            $flag = intval($_GET['flag']);        }        if($flag || $flag === 0)        {            call_user_func_array($this->hooks[$flag], $this->args[$flag]);        }        else        {            for($i = 0, $size = count($this->hooks); $i < $size; $i++)            {                $fp=fsockopen($_SERVER['HTTP_HOST'],$_SERVER['SERVER_PORT']);                if($fp)                {                    $out = "GET {$_SERVER['PHP_SELF']}?flag=$i HTTP/1.1\r\n";                    $out .= "Host: {$_SERVER['HTTP_HOST']}\r\n";                    $out .= "Connection: Close\r\n\r\n";                    fputs($fp,$out);                    fclose($fp);                }            }        }    }}$thread = new thread();$thread->addthread('func1','info1');$thread->addthread('func2','info2');$thread->addthread('func3','info3');$thread->runthread();//说明://addthread是添加线程函数,第一个参数是函数名,之后的参数(可选)为传递给指定函数的参数。//runthread是执行线程的函数。

本文由搞代码提供,介绍了如何使用PHP模拟出多线程功能。

文章地址:http://www.gaodaima.com/php-weizijiaocheng-377481.html

学编程就来搞代码 http://www.gaodaima.com

以上就是单线程的编程语言php是如何实现多线程操作的的详细内容,更多请关注搞代码gaodaima其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:单线程的编程语言php是如何实现多线程操作的

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址