upstream nginx-0.7.31
[nginx.git] / nginx / src / core / ngx_spinlock.c
1
2 /*
3  * Copyright (C) Igor Sysoev
4  */
5
6
7 #include <ngx_config.h>
8 #include <ngx_core.h>
9
10
11 void
12 ngx_spinlock(ngx_atomic_t *lock, ngx_atomic_int_t value, ngx_uint_t spin)
13 {
14
15 #if (NGX_HAVE_ATOMIC_OPS)
16
17     ngx_uint_t  i, n;
18
19     for ( ;; ) {
20
21         if (*lock == 0 && ngx_atomic_cmp_set(lock, 0, value)) {
22             return;
23         }
24
25         if (ngx_ncpu > 1) {
26
27             for (n = 1; n < spin; n <<= 1) {
28
29                 for (i = 0; i < n; i++) {
30                     ngx_cpu_pause();
31                 }
32
33                 if (*lock == 0 && ngx_atomic_cmp_set(lock, 0, value)) {
34                     return;
35                 }
36             }
37         }
38
39         ngx_sched_yield();
40     }
41
42 #else
43
44 #if (NGX_THREADS)
45
46 #error ngx_spinlock() or ngx_atomic_cmp_set() are not defined !
47
48 #endif
49
50 #endif
51
52 }