[PATCH 2 of 2] Core: add ngx_atomic_store() and ngx_atomic_load()

Maxim Dounin mdounin at mdounin.ru
Mon Sep 12 15:50:03 UTC 2016


Hello!

On Wed, Aug 17, 2016 at 05:29:32PM -0700, Piotr Sikora wrote:

> # HG changeset patch
> # User Piotr Sikora <piotrsikora at google.com>
> # Date 1471265532 25200
> #      Mon Aug 15 05:52:12 2016 -0700
> # Node ID 40765d8ee4dd29089b0e60ed5b6099ac624e804e
> # Parent  2f2ec92c3af93c11e195fb6d805df57518fede7c
> Core: add ngx_atomic_store() and ngx_atomic_load().
> 
> Those functions must be used to prevent data races between
> threads operating concurrently on the same variables.
> 
> No performance loss measured in microbenchmarks on x86_64.
> 
> No binary changes when compiled without __atomic intrinsics.
> 
> Found with ThreadSanitizer.
> 
> Signed-off-by: Piotr Sikora <piotrsikora at google.com>

[...]

>  #define ngx_trylock(lock, value)                                              \
> -    (*(lock) == 0 && ngx_atomic_cmp_set(lock, 0, value))
> +    (ngx_atomic_load(lock) == 0 && ngx_atomic_cmp_set(lock, 0, value))

The "*(lock) == 0" check here is just an optimization, it only 
ensures that the lock is likely to succed.  Atomicity is provided 
by the ngx_atomic_cmp_set() operation following the check.  If the 
check returns a wrong result due to non-atomic load - this won't 
do any harm.  The idea is that a quick-and-dirty non-atomic 
reading can be used to optimize things when the lock is already 
obtained by another process.  This is especially important in 
spinlocks like in ngx_shmtx_lock().

The same is believed to apply to the other places changed as well.  
If you think there are places where atomic reading is critical - 
please highlight these particular places.

-- 
Maxim Dounin
http://nginx.org/



More information about the nginx-devel mailing list