PHP Pthread Multithreading (a) Basic introduction

Source: Internet
Author: User
Tags flock

We can enable PHP to support multithreading by installing the pthread extension.

A thread, sometimes called a lightweight process, is the smallest unit that a program executes.a thread is an entity in a process, a basic unit that is dispatched and dispatched independently by the system, and the thread itself does not own system resources, and it shares all the resources owned by the process with other threads of the same process. One thread can create and revoke another thread, which can be executed concurrently between multiple threads in the same process. Each program has at least one thread, which is the program itself, often called the main thread. A thread is a single sequential control flow in a program. Running multiple threads at the same time in a single program accomplishes different tasks, called multithreading.
The <?php//implementation multithreading must inherit the thread class, type class test extends thread {public    function __construct ($arg) {        $this->arg = $arg;    }    When the Start method is called, the code in the object's Run method executes asynchronously in a separate thread. Public    function Run () {        if ($this->arg) {            printf ("Hello%s\n", $this->arg);        }    }} $thread = new Test ("World"), if ($thread->start ()) {    The//join method is to allow the current main thread to wait for the thread to finish    //confirm that the thread executing the join IS finished, And the thread execution sequence is okay. //    that is, when the main thread needs the processing results of the child threads, the main thread needs to wait for the child thread to finish    //Get the result of the child thread, and then process the subsequent code.    $thread->join ();}? >

Let's modify the above code to see the effect

<?phpclass Test extends Thread {public    function __construct ($arg) {        $this->arg = $arg;    }    Public Function Run () {        if ($this->arg) {            sleep (3);            printf ("Hello%s\n", $this->arg);}}}    $thread = new Test ("World"), $thread->start (); echo "Main thread\r\n";? >
We call the Start method directly without calling join. The main thread does not wait, but it outputs the main thread. The child thread waits 3 seconds before outputting Hello world. Example 1 is as follows:
<?phpclass Test extends Thread {    private $name = ';    Private $res = null;    Public function __construct ($name, $res) {        $this->name = $name;        $this->res = $res;    }    Public Function run () {while        (!feof ($this->res)) {            if (flock ($this->res, lock_ex)) {                $data = fgets ($ This->res);                $data = Trim ($data);                echo "Thread {$this->name} Read {$data} \ r \ n";                Sleep (1);                Flock ($this->res, Lock_un);}}}    $fp = fopen ('./test.log ', ' RB '); $threads [] = new Test (' a ', $fp); $threads [] = new Test (' B ', $fp); foreach ($threads as $threa d) {    $thread->start ();} foreach ($threads as $thread) {    $thread->join ();}? >
We read the contents of the file Test.log by creating two threads A and B. (* Note that when reading and writing files concurrently, be sure to lock the files.) This adds an exclusive lock to the file, and if the shared lock will appear to read the same data.)the contents of Test.log are as follows:
111111222222333333444444555555666666
The results of the implementation are as follows: Example 2:
<?phpclass Total extends Thread {public $name = ';    Private $total = 0;    Private $startNum = 0;    Private $endNum = 0;        Public function __construct ($name, $startNum, $endNum) {$this->name = $name;        $this->startnum = $startNum;    $this->endnum = $endNum; Public Function Run () {for ($ix = $this->startnum; $ix < $this->endnum; + + $ix) {$this        Total + = $ix;    } echo "Thread {$this->name} total: {$this->total} \ r \ n";    } public Function Gettotal () {return $this->total; }} $num = 10000000; $threadNum = ten; $setp = $num/$threadNum; $startNum = 0; $startTime = Microtime (True); for ($ix = 0; $ix &l T $threadNum;    + + $ix) {$endNum = $startNum + $setp;    $thread = new Total ($ix, $startNum, $endNum);    $thread->start ();    $startNum = $endNum; $threads [] = $thread;}    $total = 0;foreach ($threads as $thread) {$thread->join (); $total + = $thread->gettotal ();} $endTime = MicRotime (true); $time = $endTime-$startTime; echo "total: {$total} time: {$time} \ r \ n"; 
We create 10 threads, calculate the sum separately, and then the main thread calculates the results of 10 threads together to get the final result. We do not use multi-threading to calculate this summation and the code is as follows:
<?php$total = 0; $startTime = Microtime (True); for ($ix = 0; $ix < 10000000; + + $ix) {    $total + = $ix;} $endTime = Microtime (true); $time = $endTime-$startTime; echo "total: {$total} time: {$time} \ r \ n";

We can see that using multithreading and not using, the results are the same, but processing time, multithreading is much slower. (* Mainly the creation of threads is also required resources, and the switch between threads also takes time, here is the example of how to assign a problem to a number of sub-threads to deal with, and then the main thread to get the results of the child threads and processing to get the results we need. )

  

PHP Pthread Multithreading (a) Basic introduction

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.