Multithreaded Programming-PHP implementation

Source: Internet
Author: User

Objective

A few days ago to help colleagues check a problem, the first contact with the PHP multi-threading, the original thought that PHP is generally a single-threaded model, not suitable for multi-threaded domain, spend some time to turn over a few multi-threaded project source code, found that the multi-threaded PHP is also quite desirable, use up, to solve some problems are very suitable

So I looked for a few articles to see the implementation of the PHP multithreading TSRM mechanism, but also some gains, the details can be viewed in the following reference article. In this paper, we introduce the advantages and application scenarios of multithreading under multi-process, and propose a ingenious scheme, and use PHP code to realize the common usage of multithreading.

Article welcome reprint, but please indicate source: http://www.cnblogs.com/zhenbianshu/p/7978835.html, thank you.

multithreaded threads

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. Due to 线程是操作系统能够进行调度的最小单位 :

    • 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:

sumSmallis 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 needs to install the pthread extension, and to install the pthread extension, you must use the parameters to recompile --enable-maintainer-zts PHP, this parameter is to compile PHP using a thread-safe way.

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:

    1. There is a global array $arr = array(‘a‘); ;
    2. A thread gets an array length of 1;
    3. The B thread gets an array length of 1;
    4. A thread pops An array of elements $a = array_pop($arr); $a = ‘a‘; ;
    5. The B thread is also a pop array element $b = array_pop($arr); $a = null; ;
    6. 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 the use of TSRM mechanisms to 全局变量和静态变量进行了隔离 copy global variables and static variables to each thread, each thread uses a backup of the main thread, thus avoiding variable collisions and no thread safety issues.

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, TSRM There are additional losses when using mechanisms to allocate and use variables, so it is good to use PHP's ZTS (non-thread-safe) version in a PHP environment that does 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 pass 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 within the main thread to start running a thread;
    • join(): Each line threads is executed asynchronously for the main thread, and calling this method waits for the thread execution to finish;
    • kill(): Force thread to end;
    • isRunning(): Returns the running state of the thread, which run() returns True when the thread is executing the code of the 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 extended in-band Pool class 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:

classRequestextendsThread { Public $url;  Public $response;  Public function__construct ($url) {        $this->url =$url; }     Public functionrun () {$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 CURLOPT_CONNECTTIMEOUT / CURLOPT_TIMEOUT set the connection time-out time of curl and the read data time-out by using the parameters, 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).

At this point we can borrow multithreading to implement this function: After executing the method of the thread class start() , the method is not called join() , so that the thread is always in an asynchronous state, and does not block 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=NewRequest ("www.google.com");$chB=NewRequest ("www.baidu.com");$chG-start ();$chB-start ();$chB-Join();//The join method is not performed here for ChgSleep(1);//sleep a time-out that can be accepted$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 =_=.

Recently in the re-learning of the operating system and Linux kernel knowledge, the understanding of the program has greatly improved, it is necessary to summarize, please look forward to.

About this article has any questions can be in the following message exchange, if you think this article is helpful to you, you can click on the following 推荐 support me, blog has been updated, welcome 关注 .

Reference:

In-depth study of the threading security model for PHP and Zend engine

PHP Advanced Programming Multi-Threading

Multithreaded Programming-PHP implementation

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.