Multithreading in php and multithreading in php

Source: Internet
Author: User
Tags php multithreading

Multithreading in php and multithreading in php

Use the Socket method of php to implement multithreading of php programs. Php itself does not support multithreading. How can we implement multithreading in php? The WEB server itself supports multiple threads. Every visitor accesses the WEB page and calls a new thread. Through this, we can use the thread of the WEB server to solve the problem that PHP does not support multithreading.
 
The following is a PHP multi-threaded code that uses fsockopen () to establish a socket connection and then uses fputs () to send messages:
$ Fp = fsockopen ($ _ SERVER ['HTTP _ host'], 80, & $ errno, & $ errstr, 5 );
If (! $ Fp ){
Echo "$ errstr ($ errno) <br/> \ n ";
}
Fputs ($ fp, "GET $ _ SERVER [PHP_SELF]? Flag = 1 \ r \ n ");
Fclose ($ fp );



The above code is only a thread operation process. A few more such operations are multithreading. Currently, the so-called PHP multi-threaded program is based on this method.

The following is a complete thread-class code.
<? Php
/**
@ Title: PHP multithreading class (Thread)
@ Version: 1.0
@ Author: axgle <axgle@126.com>
*/
Class thread {
Var $ count;
Function thread ($ count = 1 ){

$ This-> count = $ count;
}

Function _ submit (){
For ($ I = 1; $ I <= $ this-> count; $ I ++) $ this-> _ thread ();
Return true;
}


Function _ thread (){
$ Fp = fsockopen ($ _ SERVER ['HTTP _ host'], 80, & $ errno, & $ errstr, 5 );

If (! $ Fp ){
Echo "$ errstr ($ errno) <br/> \ n ";
}
Fputs ($ fp, "GET $ _ SERVER [PHP_SELF]? Flag = 1 \ r \ n ");
Fclose ($ fp );
}

Function exec ($ func ){
Isset ($ _ GET ['flag'])? Call_user_func ($ func): $ this-> _ submit ();
}


}

// Application example:
$ Th = new thread (10); // 10 threads
$ Th-> exec ('Demo'); // executes a row-defined function.

Function demo (){
Fopen ('data/'. microtime (), 'w ');
}

?>

Http://codechina.spaces.live.com/blog/cns! Bca6db10a924c24! 575. entry

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.