PHP support for multithreaded programming and the use of

Source: Internet
Author: User
In the field of PHP, the concept of multithreading is not known as other languages. This thought that PHP is generally a single-threaded model, not suitable for multi-threaded domain. After a number of multi-threaded project source code, found that the multi-threaded PHP is also useful. Use it to solve some problems that are very suitable for them.

Multithreading

Thread

First, the thread:

Thread is the smallest unit in which the operating system is able to perform operational scheduling. It is included in the process and is the actual operating unit of the process. A thread refers to a single sequential control flow in a process in which multiple threads can be concurrent and each thread performs different tasks in parallel.

The use of multithreading is mainly because it has a great advantage in execution efficiency. Because the thread is the smallest unit that the operating system can schedule:

A multithreaded program is more likely to be dispatched by the OS than a single-threaded program, so multithreaded programs are generally more efficient than single-threaded procedures.

Multi-threaded threads can run simultaneously on multiple cores of multi-core CPUs, which will give full play to the advantages of machine multicore;

At the same time, compared with multi-process programs, multithreading has the following features:

The overhead of creating and switching threads is smaller than the process, so it is more efficient to a certain extent than many processes.

Threads are inherently shared memory space, and communication between threads is simpler, avoiding the introduction of new complexities in process IPC.

Applicable scenarios

Multi-threaded optimization is a lot, but no brain use multithreading can not improve the execution efficiency of the program, because the creation and destruction of threads, context switches, thread synchronization and so on are also performance loss, time-consuming may be more than the sequential execution of code. Such as:

Sumsmall is a function that accumulates from 1 to 50000.

In the main thread is executed three times sumsmall and three threads respectively execute Sumsmall, and then synchronize the results to a thread of time comparison, we will find that only the main thread execution time is shorter, three threads create, switch, synchronization time is far greater than the thread of asynchronous execution save time.

While the function Sumlarge from 1 to 5000000, the same thread executes three times and three threads execution time:

This time, multithreading finally has the advantage of efficiency.

The use of multithreading also needs to be based on specific requirements, generally consider the following two scenarios:

I/O blocking causes the operating system to schedule task scheduling, blocking the current task, so in the case of multiple I/O in code, the code can be parallelized when using multiple threads. For example, read the entire block of files multiple times, or request multiple network resources.

Multithreading can take full advantage of the CPU, so there are many large computational code, you can also use multithreading to enable them to execute in parallel, such as the previous example above.

Multi-threaded in PHP

PHP does not support multi-threading by default, to use multithreading requires the installation of the pthread extension, and to install the pthread extension, PHP must be recompiled with the--enable-maintainer-zts parameter, which specifies how to use thread-safe mode when compiling PHP.

Thread Safety

Multithreading is a factor that makes programs restless, and before you use multithreading, you should first consider thread-safety issues:

Thread Safety: Thread safety is the term in programming, when a function or library is called in a multithreaded environment, it is able to correctly handle shared variables between multiple threads, so that the program function is completed correctly.

In traditional multi-threading, because multiple threads share variables, this can cause the following problems to occur:

There is a global array $arr = Array (' a ');;

A thread gets an array length of 1;

The B thread gets an array length of 1;

A thread POPs array element $a = Array_pop ($arr); $a = ' a ';;

The B thread is also a pop array element $b = Array_pop ($arr); $a = null;;

At this point in the B thread there is a supernatural event, clearly array length is greater than 0, or no pop out of things;

PHP implementation

The thread security implemented by PHP is mainly to use the TSRM mechanism to isolate global variables and static variables, to copy global variables and static variables to each thread, each thread uses a backup of the main thread, thus avoiding variable collisions, and there is no thread-safety issue.

PHP's encapsulation of multithreading guarantees thread safety, and programmers do not have to consider adding locks to global variables to avoid read and write collisions, and also reduce the chance of errors and write code more securely.

The result is that once the child thread starts running, the main thread can no longer adjust the details of the child thread, and the thread loses the ability to pass the global variable for message delivery to some extent.

While PHP turns on thread-safe options, there are additional losses when allocating and using variables using the TSRM mechanism, so it is good to use PHP's ZTS (non-thread-safe) version in PHP environments that do not require multi-threading.

Classes and methods

PHP encapsulates threads into thread classes, and threads are created by instantiating a thread object, and because of the encapsulation of classes, the use of variables can only be passed through constructors, and the results of threading operations need to be passed through class variables.

Here are a few common Thread class methods:

Run (): This method is an abstract method in which each thread implements this method, and the code in this method executes automatically after the thread starts running; start (): Call this method in the main thread to start running a thread; join (): Each line threads is executed asynchronously for the main thread. Calling this method waits for the thread to execute, kill (): Forces the thread to end, IsRunning (): Returns the running state of the thread, and returns True when the thread is executing the code of the Run () method;

Because of the thread-safe implementation, PHP's multithreading begins to run, no longer communicates through shared memory space, and threads cannot be reused through inter-thread communication, so I don't think PHP's "thread pool" makes any sense. The pool class within the extension is a class for multi-threaded allocation management and is no longer introduced here.

Instance Code

The following is a thread class that is used to request an interface. Next, write two multi-threaded application instances based on it:

Class Request extends Thread {public    $url;    public $response;    Public function __construct ($url) {        $this->url = $url;    }    Public Function Run () {        $this->response = file_get_contents ($this->url);}    }

Asynchronous request

The synchronous request is split into multiple threads for asynchronous calls to increase the efficiency of the program's operation.

$chG = new Request ("www.google.com"), $chB = new request ("www.baidu.com"), $chG->start (); $chB->start (); $chG Join (); $chB->join (); $gl = $chG->response; $bd = $chB->response;

Timeout control

Accidental discovery of a piece of content on a Web page of a company's website is sometimes not known, but it gives me the inspiration to use Multithreading: fast failure and timeout control with thread async.

When we use curl to request an address, we can set the connection time-out time and read data time-out time of curl by using the Curlopt_connecttimeout/curlopt_timeout parameter, but the total timeout time is not control. And the time-out during database queries cannot be set (Bird blog: Set query timeout for MySQL).

We can then borrow multithreading to do this: after the start () method of the thread class is executed, the join () method is not called, leaving the thread in an asynchronous state without blocking the execution of the main thread.

At this time the main thread equivalent to the flagship, and each sub-thread equivalent to a cruise ship, the flagship arrived in a place after the need to wait for the cruise ship also return, waiting for a period of time to leave, so as to avoid the flagship of cruise ship accidentally empty space.

Code:

$chG = new Request ("www.google.com"), $chB = new request ("www.baidu.com"), $chG->start (); $chB->start (); $chB Join ();//This does not perform a join method for CHG sleep (1); Sleep an acceptable time-out $GL = $chG->response; $bd = $chB->response; $bd->kill (), if (! $gl) {    $GL = ""; Handle exceptions, or give $GL a default value within the thread class}

Summarize

PHP Yan (GE) for multithreading, which makes it very uncomfortable for people to use threads. Although security, but also keep PHP simple and easy to use the consistent style, but can not fully play the ability of multi-threading. But each language has the characteristic and the emphasis, also does not need to insist, loves her to contain her =_=.

Related recommendations:

PHP Asynchronous multithreaded Swoole Usage example

Implementing a PHP Multithreaded class case

PHP Multithreading Small case

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.