Multi-thread programming,

Source: Internet
Author: User
Tags php multithreading zts

Multi-thread programming,
Preface

I checked a problem with my colleagues the other day. I first came into contact with the multithreading of PHP. I thought that PHP is generally a single-thread model and is not suitable for multithreading. After I spent some time turning over the source code of several multi-threaded projects, I found that PHP multithreading is also quite desirable. It is very suitable to solve some problems.

So I found several articles and read PHP multithreading.TSRMThe implementation of the Mechanism also gains some benefits. For details, refer to the following reference article. This article compares multiple processes, introduces the advantages and applicable scenarios of multithreading, proposes a clever use scheme, and uses PHP code to implement the common usage of multithreading.

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

Multi-thread

First, let's talk about the thread:

A thread is the smallest unit that the operating system can schedule operations. 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. A process can be concurrently executed by multiple threads, and each thread executes different tasks in parallel.

Multithreading is mainly used because it has a great advantage in execution efficiency. BecauseA thread is the smallest unit that the operating system can schedule.:

  • A multi-threaded program has a higher probability of being scheduled by the operating system than a single-threaded program. Therefore, a multi-threaded program is generally more efficient than a single-threaded program;
  • Multiple Threads of a multi-threaded program can run at the same time on multiple cores of a multi-core CPU. This gives full play to the advantages of multiple cores of the machine;

Compared with multi-process programs, multithreading has the following features:

  • The system overhead of thread creation and switching is lower than that of process, so it is more efficient than multi-process to a certain extent;
  • Threads naturally share memory space, making inter-thread communication easier, avoiding the new complexity introduced by the process IPC.
Applicable scenarios

There are many optimizations for multithreading, but the brainless use of multithreading cannot improve the execution efficiency of the program, because the creation and destruction of threads, context switching, thread synchronization, and so on also have performance loss, it may take more time than code executed in sequence. For example:

sumSmallIs a function that accumulates from 1 to 50000.

Three sumSmall is executed in the main thread and three sumSmall are executed respectively, and the result is synchronized to the time comparison of one thread, we will find that the execution time is shorter only in the main thread. The time for creating, switching, and synchronizing the three threads is much longer than the time saved by asynchronous thread execution.

While the sumLarge function accumulates from 1 to 5000000, the time consumed by the same thread to execute three times and three threads:

This time, multithreading is finally an efficient advantage.

Whether to use multithreading depends on the specific needs. Generally, the following two situations are considered:

  • I/O blocking will cause task scheduling in the operating system, blocking the current task, so when there are many I/O in the code, the code can be parallel when multithreading is used. For example, you can read the entire block multiple times or request multiple network resources.
  • Multithreading can make full use of the CPU, so when there are multiple large amounts of computing code, you can also use multithreading to execute them in parallel, for example, the following example.
Multithreading in PHP

By default, PHP does not support multithreading. To use multithreading, you need to install the pthread extension. to install the pthread extension, you must use--enable-maintainer-ztsRe-compile the PHP parameter. This parameter specifies the thread security mode used for PHP compilation.

Thread Security

Multithreading is a factor that makes the program restless. Before using multithreading, you must first consider the thread security issue:

Thread security: thread security is a term used in programming. When a function or function library is called in a multi-threaded environment, it can correctly process shared variables among multiple threads, make the program function complete correctly.

In traditional multithreading, as multiple threads share variables, the following problems may occur:

PHP implementation

Thread security implemented by PHP is mainly usedTSRMMechanism pairGlobal variables and static variables are isolated.The global variables and static variables are copied to each thread. Each thread uses a backup of the main thread to avoid variable conflicts and avoid thread security issues.

PHP's multi-thread encapsulation ensures thread security. programmers do not need to consider adding various locks to global variables to avoid read/write conflicts. It also reduces the chance of errors and makes the written code safer.

However, once the sub-thread starts running, the main thread cannot adjust the running details of the sub-thread, to some extent, threads lose the ability to transmit messages through global variables between threads.

When the thread security option is enabled in PHPTSRMThe Mechanism also causes additional losses when allocating and using variables. Therefore, in a PHP environment that does not require multithreading, use PHP's ZTS (non-thread-safe) version.

Classes and Methods

PHP encapsulates threadsThreadClass, the thread is created by instantiating a thread object. Due to the encapsulation of the class, the use of variables can only be passed through the constructor, And the thread operation result must also be passed through the class variable.

The following describes several common Thread methods:

  • run(): This method is an abstract method. Every thread must implement this method. After the thread starts running, the code in this method is automatically executed;
  • start(): Call this method in the main thread to start running a thread;
  • join(): Each thread is asynchronously executed relative to the main thread. Calling this method will wait until the thread execution ends;
  • kill(): Force the thread to end;
  • isRunning(): Return the running status of the thread. The thread is executing.run()The return value is true;

Due to the implementation of thread security, after the PHP multi-thread starts to run, it can no longer communicate through the shared memory space, and threads cannot be reused through inter-thread communication, so I think PHP's "Thread Pool" does not make any sense. Built-in ExtensionPoolA class is a management class for multi-thread allocation.

Instance code

The following is a thread class 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

Split the synchronous request into multiple threads for asynchronous calling to improve the program running efficiency.

$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

Occasionally, I found that a piece of content on a webpage of the company's website was not available and I did not know the specific implementation. However, this inspired me to use multithreading: Using thread Asynchronization to achieve fast failure and time-out control.

When we use curl to request an addressCURLOPT_CONNECTTIMEOUT / CURLOPT_TIMEOUTThe parameters respectively set the curl connection timeout and data read timeout, but the overall timeout is not well controlled. In addition, the timeout time cannot be set during database query (laruence blog: Set query timeout for MySQL ).

In this case, we can use multiple threads to implement this function:start()Method, do not calljoin()Method To keep the thread in asynchronous state without blocking the execution of the main thread.

At this time, the main thread is equivalent to the flagship, and each sub-thread is equivalent to the patrol ship. After the flagship arrives somewhere, it does not have to wait until the patrol ship returns. Wait for a while before leaving, in this way, the flagship ship can be empty in case of an accident.

Code:

$ ChG = new Request ("www.google.com"); $ chB = new Request ("www.baidu.com"); $ chG-> start (); $ chB-> start (); $ chB-> join (); // The join method sleep (1) is not executed for chG. // an acceptable timeout value for sleep $ gl = $ chG-> response; $ bd = $ chB-> response; $ bd-> kill (); if (! $ Gl) {$ gl = ""; // handle exceptions, or give $ gl a default value in the Thread class}
Summary

PHP's multi-thread sealing (yan) assembly (ge) makes it very difficult to use threads. Although it is safe and consistent with PHP's simple and easy-to-use style, it cannot fully utilize the multi-thread capability. However, each language has its own characteristics and focus, and you do not have to insist on it. If you love her, you must include her ====.

Recently, I have learned a lot about operating systems and Linux kernel, and I have improved my understanding of the program. I feel it is very necessary to summarize it. Please stay tuned.

If you have any questions about this article, please leave a message below. If you think this article is helpful to you, clickRecommendationSupport me. My blog has been updated. Welcome.Follow.

Refer:

In-depth study of the thread security model of PHP and Zend Engine

Multithreading in PHP Advanced Programming

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.