단일 스레드 프로그래밍 언어 PHP는 다중 스레드 작업을 어떻게 구현합니까?

PHP中文网
풀어 주다: 2023-03-15 15:16:01
원래의
2437명이 탐색했습니다.

언어 PHP 자체는 하나의 작업이 완료된 후 다음 작업이 실행될 수 있다는 것을 누구나 알고 있습니다.

그러나 때로는 비동기 작업과 동시에 실행되는 여러 스레드가 필요합니다.

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에서 제공됩니다. 중국어 웹사이트, PHP를 사용하여 멀티스레딩 기능을 시뮬레이션하는 방법을 소개합니다.

글 주소: http://www.php.cn/php-weizijiaocheng-377481.html

프로그래밍을 배우려면 PHP 중국어 웹사이트 www.php.cn

를 방문하세요.

위 내용은 단일 스레드 프로그래밍 언어 PHP는 다중 스레드 작업을 어떻게 구현합니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!