Nginx spinlock互斥锁

在nginx里面,定义了一个spinlock,来同步父子进程间的共享内存操作

C代码   收藏代码
  1. #define ngx_shmtx_lock(mtx) ngx_spinlock((mtx)->lock, ngx_pid, 1024)  
C代码   收藏代码
  1. void ngx_spinlock(ngx_atomic_t *lock, ngx_atomic_int_t value, ngx_uint_t spin)  
  2. {  
  3. #if (NGX_HAVE_ATOMIC_OPS)  
  4.     ngx_uint_t  i, n;  
  5.     for ( ;; ) {  
  6.         //__sync_bool_compare_and_swap(lock, old, set)  
  7.         //这是原子操作  
  8.         //尝试把lock的值设置成value,如果不为0就说明已经有其他进程获取了该锁  
  9.         if (*lock == 0 && ngx_atomic_cmp_set(lock, 0, value)) {  
  10.             //获取锁成功  
  11.             return;  
  12.         }  
  13.   
  14.         if (ngx_ncpu > 1) {  
  15.             //spin=1024,每次shift一位  
  16.             for (n = 1; n < spin; n <<= 1) {  
  17.                 //n=1,2,4,8,16,32,64,128 ...  
  18.                 //每次等待时间增加一倍  
  19.                 for (i = 0; i < n; i++) {  
  20.                     //__asm__(".byte 0xf3, 0x90")  
  21.                     //__asm__("pause")  
  22.                     //等待一段时间  
  23.                     ngx_cpu_pause();  
  24.                 }  
  25.                 //等待一段时间再去尝试获取锁  
  26.                 if (*lock == 0 && ngx_atomic_cmp_set(lock, 0, value)) {  
  27.                     //获取锁成功  
  28.                     return;  
  29.                 }  
  30.             }  
  31.         }  
  32.         //试了这么多次,还是没有获取锁,那就休息一下吧  
  33.         //sched_yield()  
  34.         //usleep(1)  
  35.         ngx_sched_yield();  
  36.     }  
  37. #else  
  38. #if (NGX_THREADS)  
  39. #error ngx_spinlock() or ngx_atomic_cmp_set() are not defined !  
  40. #endif  
  41. #endif  

猜你喜欢

转载自zzc1684.iteye.com/blog/2164175