Multi-threaded time update model in Nginx

Source: Internet
Author: User
Tags php tutorial
In Nginx, the Ngx_time_update function can be executed by multiple threads, but as long as one thread executes the function, the other thread does not need to execute the function.

For this kind of demand, Nginx gives the implementation of the scheme is very interesting.

Ngx_time_update begins with two sentences as follows:

    if (!ngx_trylock (&ngx_time_lock)) {        return;    }    Do something    ... Ngx_unlock (&ngx_time_lock);

Ngx_trylock and Ngx_unlock are macro definitions and the code is as follows:

#define NGX_TRYLOCK (Lock)  (* (lock) = = 0 && ngx_atomic_cmp_set (lock, 0, 1) #define NGX_UNLOCK (Lock)    * ( Lock) = 0
Continue to expand Ngx_atomic_cmp_set

#define NGX_ATOMIC_CMP_SET (lock, old, set)                                    \     ((ngx_atomic_uint_t) InterlockedCompareExchange ((long *) lock, Set, old) \                          = = old)

ngx_atomic_uint_t is the type alias of the unsigned int.

At this point, we can see that this synchronization scheme is implemented using InterlockedCompareExchange.

First, the Interlocked series function guarantees the atomicity of the operation.

Assuming that the value of the Ngx_time_lock variable is now 0, there are two threads that are going to execute the InterlockedCompareExchange function. At this point, only one thread executes first, it changes the value of Ngx_time_lock to 1, and returns 0. Another thread compares the new Ngx_time_lock value (that is, 1) with 0, at which point the interchange does not occur and the original value of 1 is returned, ensuring that the thread returns at the if judgment.

In addition, the type of ngx_atomic_t is defined as: typedef volatile unsigned int ngx_atomic_t;


The above describes the Nginx in the multi-threaded time update model, including the aspects of the content, I hope that the PHP tutorial interested in a friend helpful.

  • Related Article

    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.