ホームページ  >  記事  >  バックエンド開発  >  シングルスレッド プログラミング言語 PHP はどのようにマルチスレッド操作を実装するのでしょうか?

シングルスレッド プログラミング言語 PHP はどのようにマルチスレッド操作を実装するのでしょうか?

PHP中文网
PHP中文网オリジナル
2017-08-26 09:30:122425ブラウズ

PHP 言語自体はシングルスレッドでしか動作できないことは誰もが知っています。1 つの操作が完了すると、次の操作が実行されます。

しかし、場合によっては、非同期操作と複数のスレッドの同時実行が必要になることがあります

PHP がマルチスレッド操作を実装する方法を紹介しましょう

コードは次のとおりです: 参考のみです

<?php
/**
 * @title:        PHP多线程类(Thread)
 * @version:    1.0
 * @author:        php.cn < web@php.cn >
 * @published:    2010-11-2
 * 
 * PHP多线程应用示例:
 *  require_once &#39;thread.class.php&#39;;
 *  $thread = new thread();
 *  $thread->addthread(&#39;action_log&#39;,&#39;a&#39;);
 *  $thread->addthread(&#39;action_log&#39;,&#39;b&#39;);
 *  $thread->addthread(&#39;action_log&#39;,&#39;c&#39;);
 *  $thread->runthread();
 *  
 *  function action_log($info) {
 *      $log = &#39;log/&#39; . microtime() . &#39;.log&#39;;
 *      $txt = $info . "\r\n\r\n" . &#39;Set in &#39; . Date(&#39;h:i:s&#39;, time()) . (double)microtime() . "\r\n";
 *      $fp = fopen($log, &#39;w&#39;);
 *      fwrite($fp, $txt);
 *      fclose($fp);
 *  }
 */
class thread {
    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[&#39;flag&#39;]))
        {
            $flag = intval($_GET[&#39;flag&#39;]);
        }
        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[&#39;HTTP_HOST&#39;],$_SERVER[&#39;SERVER_PORT&#39;]);
                if($fp)
                {
                    $out = "GET {$_SERVER[&#39;PHP_SELF&#39;]}?flag=$i HTTP/1.1\r\n";
                    $out .= "Host: {$_SERVER[&#39;HTTP_HOST&#39;]}\r\n";
                    $out .= "Connection: Close\r\n\r\n";
                    fputs($fp,$out);
                    fclose($fp);
                }
            }
        }
    }
}
$thread = new thread();
$thread->addthread(&#39;func1&#39;,&#39;info1&#39;);
$thread->addthread(&#39;func2&#39;,&#39;info2&#39;);
$thread->addthread(&#39;func3&#39;,&#39;info3&#39;);
$thread->runthread();
//说明:
//addthread是添加线程函数,第一个参数是函数名,之后的参数(可选)为传递给指定函数的参数。
//runthread是执行线程的函数。

この記事は PHP によって提供されています。中国の Web サイトでは、PHP を使用してマルチスレッド機能をシミュレートする方法を紹介しています。

記事のアドレス: http://www.php.cn/php-weizijiaocheng-377481.html

プログラミングを学ぶには、PHP 中国語 Web サイト www.php.cn

にアクセスしてください。

以上がシングルスレッド プログラミング言語 PHP はどのようにマルチスレッド操作を実装するのでしょうか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。