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
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.
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
The lock provided by the system interface will generally suspend the thread when the lock fails, similar to
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.