Multithreading time update model in nginx

Source: Internet
Author: User
: This article mainly introduces the multithreaded time update model in nginx. For more information about PHP tutorials, see. In nginx, the ngx_time_update function can be executed by multiple threads, but as long as one thread executes this function, other threads do not need to execute this function.

The implementation scheme provided by nginx is quite interesting for this requirement.

The first two sentences of ngx_time_update are as follows:

    if (!ngx_trylock(&ngx_time_lock)) {        return;    }    // do something...    ngx_unlock(&ngx_time_lock);

Both ngx_trylock and ngx_unlock are MACRO Definitions. 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 alias of the unsigned int type.

So far, we can see that this synchronization scheme is implemented using InterlockedCompareExchange.

First, Interlocked functions can guarantee the atomicity of operations.

Assume that the value of the ngx_time_lock variable is 0, and there are two threads that need to execute the InterlockedCompareExchange function. At this time, only one thread executes the task first. it changes the value of ngx_time_lock to 1 and returns 0. Another thread uses the new ngx_time_lock value (that is, 1) to compare with 0. at this time, no exchange will occur and the original value 1 will be returned to ensure that this thread returns at the if judgment.

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


The above introduces the multithreading time update model in nginx, including some content, and hope to be helpful to friends who are interested in PHP tutorials.

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.