Seq锁

   Seq锁是在2.6内核版本中引入的一种新型锁。这种锁提供了一种很简单的机制,用于读写共享数据。实现这种锁主要依靠一个序列计数器。当有疑义的数据被写入时,会得到一个锁,并且序列值会增加。在读取数据之前和之后,序列号都被读取。如果序列号值相同,说明读操作进行的过程中没有被写操作打断。如果读取的值是偶数,那么就表明写操作没有发生(锁的初值是0,写锁会使值变成奇数,释放的时候变成偶数)。

 

  1. 在<Seqlock.h(include/linux)>中
  2. typedef struct {
  3.     unsigned sequence;
  4.     spinlock_t lock;
  5. } seqlock_t;
  6. /* Lock out other writers and update the count.
  7.  * Acts like a normal spin_lock/unlock.
  8.  * Don't need preempt_disable() because that is in the spin_lock already.
  9.  */
  10. static inline void write_seqlock(seqlock_t *sl)
  11. {
  12.     spin_lock(&sl->lock);
  13.     ++sl->sequence;
  14.     smp_wmb();          
  15. }   
  16. static inline void write_sequnlock(seqlock_t *sl) 
  17. {
  18.     smp_wmb();
  19.     sl->sequence++;
  20.     spin_unlock(&sl->lock);
  21. }
  22. static inline int write_tryseqlock(seqlock_t *sl)
  23. {
  24.     int ret = spin_trylock(&sl->lock);
  25.     if (ret) {
  26.         ++sl->sequence;
  27.         smp_wmb();          
  28.     }
  29.     return ret;
  30. }

写锁的方法和普通自旋锁类似,不同的情况发生在读时:

 

  1. /* Start of read calculation -- fetch last complete writer token */
  2. static __always_inline unsigned read_seqbegin(const seqlock_t *sl)
  3. {
  4.     unsigned ret = sl->sequence;
  5.     smp_rmb();
  6.     return ret;
  7. }
  8. /* Test if reader processed invalid data.
  9.  * If initial values is odd, 
  10.  *  then writer had already started when section was entered
  11.  * If sequence value changed
  12.  *  then writer changed data while in section
  13.  *    
  14.  * Using xor saves one conditional branch.
  15.  */
  16. static __always_inline int read_seqretry(const seqlock_t *sl, unsigned iv)
  17. {
  18.     smp_rmb();
  19.     return (iv & 1) | (sl->sequence ^ iv);
  20. }

在多个读者和少数写者共享一把锁的时候,seq锁有助于提供一种非常轻量和具有可扩展性的外观。但是seq锁对写者更有利。只要没有其他写者,写锁总是能够被成功获得。读者不会影响写锁。挂起的写锁会不断的使得读操作循环,直到不在有任何写者持有锁为止。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值