php多線程類的代碼分享

來源:互聯網
上載者:User
本文介紹下,有關php中實現多線程的一個類,有需要的朋友參考下。

如何通過WEB伺服器實現PHP的多線程功能呢?在php編程中,通過WEB伺服器實現的多線程只能模仿多線程的一些效果,並不是真正意義上的多線程。

在需要類似多線程的功能時,可以參考下下面的這個類。

代碼:

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 {    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);          }         }     }    }}?>

調用樣本:

addthread('func1','info1');$thread->addthread('func2','info2');$thread->addthread('func3','info3');$thread->runthread();?>

說明:addthread是添加線程函數,第一個參數是函數名,之後的參數(可選)為傳遞給指定函數的參數。runthread是執行線程的函數。

附,下載地址:php多線程類的源碼。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.