zoukankan      html  css  js  c++  java
  • xv6 锁

      在xv6 中锁对象是 spinlock,spinlock中的locked为1的时候表示被占用,为0的时候锁空闲。

    struct spinlock {
      uint locked;       // Is the lock held?
      ......
    };

      使用 acquire获取锁

    void acquire(struct spinlock *lk)
    {
      ........
      while(xchg(&lk->locked, 1) != 0);
      ......
    }

      该函数中通过xchg原子性交换locked和1,并返回locked的原来的值。当返回值为1时,说明其他线程占用了该锁,继续循环等待;当返回值为0时,说明其他地方没有占用该锁,同时locked本设置成1了,所以该锁被此处占用。

      

    static inline uint xchg(volatile uint *addr, uint newval)
    {
      uint result;
    
      // The + in "+m" denotes a read-modify-write operand.
      asm volatile("lock; xchgl %0, %1" :
                   "+m" (*addr), "=a" (result) :
                   "1" (newval) :
                   "cc");
      /*
        //最终汇编类似于
        movq    *addr, %rdx
        movl    newval, %eax
        lock; xchgl (%rdx), %eax
        movl    %eax, result
        
      */
      return result;
    }

      xchg通过lock xchg实现原子性的交换,把*addr的老值放入eax中,然后在赋值给result。

      释放锁

    void release(struct spinlock *lk)
    {
      ...
      // Release the lock, equivalent to lk->locked = 0.
      // This code can't use a C assignment, since it might
      // not be atomic. A real OS would use C atomics here.
      asm volatile("movl $0, %0" : "+m" (lk->locked) : );
      ...
    }
  • 相关阅读:
    Windows10 ntoskrnl.exe占用大量的磁盘空间(100%)
    Windows10 正式企业版激活
    edit-distance
    climbing-stairs
    minimum-path-sum
    unique-paths-II
    unique-paths
    剑指 Offer 42. 连续子数组的最大和
    剑指 Offer 54. 二叉搜索树的第k大节点
    矩阵中的路径
  • 原文地址:https://www.cnblogs.com/hygblog/p/9361888.html
Copyright © 2011-2022 走看看