Home  >  Q&A  >  body text

java - Cas操作会加锁吗

问题:
(1)不需要cas操作来加锁和解锁,这个怎么理解??cas操作不是如果比较不成功那么就一直尝试吗?和加锁有什么关系??这个该如何理解

怪我咯怪我咯2743 days ago695

reply all(1)I'll reply

  • 怪我咯

    怪我咯2017-04-18 10:54:40

    Compare and swap operations may not require locks, depending on the platform, but most platforms support lock-free cas. The simplest lock is a spin lock implemented through test and set. Of course, it can also be implemented through cas.

    Spin lock will indeed keep trying when the lock fails, exhausting CPU resources. Such as

    while (flag.test_and_set()) { /* yield; */ } // 上锁
    flag.clear(); // 解锁
    

    The lock provided by the system interface will generally suspend the thread when the lock fails, similar to

    while (flag.test_and_set()) { flag.wait_for_unlock_signal(); } // 上锁
    

    The wait_for_unlock_signal() here is an imaginary function. But locking still relies on atomic operations like cas. In other words, locks are now implemented through some basic atomic operations, such as test and set and compare and swap.

    reply
    0
  • Cancelreply