scotthuang1989 发表于 2015-02-09 22:59

回复 19# DVD0423


是否理解为当Cpu在自旋的时候,至少本地CPU的内核抢占是被禁止的。不知道这个理解是否正确。


   

DVD0423 发表于 2015-02-10 10:51

回复 4# 镇水铁牛

现在的内核自旋锁用的是ticket spinlock, 就是排队自旋锁,这样就实现了公平性,减少了锁释放时产生的cpu争用锁开销,同时在linux里如果一个自旋锁一直自旋不释放,达到一定阈值后就会进入睡眠状态,有人说睡眠了还在running,这点我表示怀疑。

我觉得只有暴露自己的错误才能进步,如果我说的不对请勿鄙视{:qq1:}
   

DVD0423 发表于 2015-02-10 11:20

回复 2# amarant
用户态(ring3)如果想使用内核(ring0)的东西,要进行系统调用,进行系统调用(中断)的开销很大,要进行用户态上下文的保存。所以我感觉用户态的自旋锁应该不会是系统调用吧(我主要研究内核态,所以不确定)。

还有大家看看我的理解是不是错的,我也想知道:在x86硬件上,操作系统运行在ring0,可以执行任何指令,而用户态运行在ring3上,只能执行自己进程相关指令,这样就保证了系统安全。同时用户态不必经过内核态,内核只是一种管理工具,只有在用户需要扩权,需要运行一些ring0的指令的时候才经过内核态,而这个途径就是系统调用。(个人见解,如果有人告诉我错了,那我才能认识的更深入)

对了,用户态调用内核态的东西是不是只有系统调用这个唯一途径?

firocu 发表于 2016-05-31 11:26

本帖最后由 firocu 于 2016-05-31 11:27 编辑

我来贴段gcc里面的实现, 可以看出来是没有差别的(FIXME):int
pthread_spin_lock (pthread_spinlock_t *lock)
{
/* atomic_exchange usually takes less instructions than
   atomic_compare_and_exchange.On the other hand,
   atomic_compare_and_exchange potentially generates less bus traffic
   when the lock is locked.
   We assume that the first try mostly will be successful, and we use
   atomic_exchange.For the subsequent tries we use
   atomic_compare_and_exchange.*/
if (atomic_exchange_acq (lock, 1) == 0)
    return 0;

do
    {   
      /* The lock is contended and we need to wait.Going straight back
         to cmpxchg is not a good idea on many targets as that will force
         expensive memory synchronizations among processors and penalize other
         running threads.
         On the other hand, we do want to update memory state on the local core
         once in a while to avoid spinning indefinitely until some event that
         will happen to update local memory as a side-effect.*/
      if (SPIN_LOCK_READS_BETWEEN_CMPXCHG >= 0)
      {
          int wait = SPIN_LOCK_READS_BETWEEN_CMPXCHG;

          while (*lock != 0 && wait > 0)
            --wait;
      }
      else
      {
          while (*lock != 0)
            ;
      }
    }   
while (atomic_compare_and_exchange_val_acq (lock, 1, 0) != 0);

return 0;
}
页: 1 2 [3]
查看完整版本: 用户态自旋锁和内核态自旋锁的区别?