Code sharing for PHP multi-threading class

WBOY
Release: 2016-07-25 08:57:25
Original
737 people have browsed it
This article introduces a class that implements multi-threading in PHP. Friends in need can refer to it.

How to implement PHP’s multi-threading function through a WEB server? In PHP programming, multi-threading implemented through the WEB server can only imitate some of the effects of multi-threading, and is not multi-threading in the true sense.

When you need functions similar to multi-threading, you can refer to the following class.

Code:

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); } } } } } ?>
Copy after login

Call example:

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

Instructions: addthread is to add a 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.

Attached, download address: source code of PHP multi-threading class.



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!