java - Cas操作会加锁吗
怪我咯
怪我咯 2017-04-18 10:52:40
0
1
692

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

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(1)
刘奇

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!