linux内核情景分析之锁机制


  1. /*
  2. * These are the generic versions of the spinlocks and read-write
  3. * locks..
  4. *///自旋锁加锁,irqsave表示把标志寄存器存储起来
  5. #define spin_lock_irqsave(lock, flags) do { local_irq_save(flags);//关闭本地中断,保存标志位 spin_lock(lock); } while (0)
  6. #define spin_lock_irq(lock) do { local_irq_disable(); spin_lock(lock); } while (0)
  7. #define spin_lock_bh(lock) do { local_bh_disable(); spin_lock(lock); } while (0)
  8. //读锁与下面写锁,构成读写锁
  9. #define read_lock_irqsave(lock, flags) do { local_irq_save(flags); read_lock(lock); } while (0)
  10. #define read_lock_irq(lock) do { local_irq_disable(); read_lock(lock); } while (0)
  11. #define read_lock_bh(lock) do { local_bh_disable(); read_lock(lock); } while (0)
  12. //写锁,与上面构成读写锁
  13. #define write_lock_irqsave(lock, flags) do { local_irq_save(flags); write_lock(lock); } while (0)
  14. #define write_lock_irq(lock) do { local_irq_disable(); write_lock(lock); } while (0)
  15. #define write_lock_bh(lock) do { local_bh_disable(); write_lock(lock); } while (0)
  16. //自旋锁解锁
  17. #define spin_unlock_irqrestore(lock, flags) do { spin_unlock(lock); local_irq_restore(flags); } while (0)
  18. #define spin_unlock_irq(lock) do { spin_unlock(lock); local_irq_enable(); } while (0)
  19. #define spin_unlock_bh(lock) do { spin_unlock(lock); local_bh_enable(); } while (0)
  20. //读锁解锁
  21. #define read_unlock_irqrestore(lock, flags) do { read_unlock(lock); local_irq_restore(flags); } while (0)
  22. #define read_unlock_irq(lock) do { read_unlock(lock); local_irq_enable(); } while (0)
  23. #define read_unlock_bh(lock) do { read_unlock(lock); local_bh_enable(); } while (0)
  24. //写锁解锁
  25. #define write_unlock_irqrestore(lock, flags) do { write_unlock(lock); local_irq_restore(flags); } while (0)
  26. #define write_unlock_irq(lock) do { write_unlock(lock); local_irq_enable(); } while (0)
  27. #define write_unlock_bh(lock) do { write_unlock(lock); local_bh_enable(); } while (0)

自旋锁加锁解析
  1. static inline void spin_lock(spinlock_t *lock)
  2. {
  3. #if SPINLOCK_DEBUG
  4. __label__ here;
  5. here:
  6. if (lock->magic != SPINLOCK_MAGIC) {//判断是否等于魔数
  7. printk("eip: %p\n", &&here);
  8. BUG();
  9. }
  10. #endif
  11. __asm__ __volatile__(
  12. spin_lock_string
  13. :"=m" (lock->lock) : : "memory");
  14. }
其中spin_lock_string为一个宏
  1. #define spin_lock_string \
  2. "\n1:\t" \
  3. "lock ; decb %0\n\t" \ //将lock->lock减1,指令带lock表示把总线锁住,禁止其他cpu访问
  4. "js 2f\n" \//不是非负数,直接进入临界区
  5. ".section .text.lock,\"ax\"\n" \
  6. "2:\t" \
  7. "cmpb $0,%0\n\t" \//如果-1结果为负数,那就循环检测
  8. "rep;nop\n\t" \
  9. "jle 2b\n\t" \//如果检测依旧是负数,跳转到2
  10. "jmp 1b\n" \//否则检测
  11. ".previous"


互斥锁,读写锁,条件变量,自旋锁(用于线程互斥)
信号量,文件锁用于进程同步




来自为知笔记(Wiz)


posted on 2016-10-27 10:54  笨拙的菜鸟  阅读(914)  评论(0编辑  收藏  举报

导航