Home > Article > Backend Development > Case study of implementing PHP multi-threading class
We have introduced to you the implementation method of PHP multi-threading and asynchronous calls before. We all know that multi-threading implemented through WEB servers can only imitate some effects of multi-threading, and is not multi-threading in the true sense. But no matter Anyway, it can still meet some of our needs, so today we will implement the PHP multi-threaded class!
php multi-threaded class:
/** * @title: PHP多线程类(Thread) * @version: 1.0 * * 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 . "rnrn" . 'Set in ' . Date('h:i:s', time()) . (double)microtime() . "rn"; * $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.1rn"; $out .= "Host: {$_SERVER['HTTP_HOST']}rn"; $out .= "Connection: Closernrn"; fputs($fp,$out); fclose($fp); } } } } }
Usage method, the code is as follows:
$thread = new thread(); $thread->addthread('func1','info1'); $thread->addthread('func2','info2'); $thread->addthread('func3','info3'); $thread->runthread();
Instructions:
addthread() is to add Thread function, the first parameter is the function name, and the subsequent parameters (optional) are the parameters passed to the specified function .
runthread() is the function of the execution thread.
Summary:
This article shares with you a PHP multi-threaded class. You don’t need to write so much code in the future. You will need it next time. You can call it directly at that time. I hope it can be helpful to you!
Related recommendations:
The above is the detailed content of Case study of implementing PHP multi-threading class. For more information, please follow other related articles on the PHP Chinese website!