同是memcached,为什么Redis放弃了CAS

  首先我们看看CAS在memcached里完成了怎样的功能:
引用
when the client performs a GET the server actually returns two values:
the value of the key itself and an integer, that is called a
"cas_token" in memcached slang, but actually it's a 64 bit integer
that you can think as a "version" of the value contained inside a key.
Every time a key is set to another thing this counter increments.

  memcached服务器端储存的是些key-value对,每次客户端get(key)时server返回了两个东西,一个是我们想要的value,还有一个叫“cas_token”,说白了了就是个64位的版本号,每次value被更新时cas_token就会++,看到++估计在座的各位就会形成条件反射了,没错、CAS这时候就可以登场了!
  在此我想先谈谈CAS,天下武功唯快不破,CAS亦是如此,不加锁的前提下假设要改变的变量是最干净的(现代CPU能侦测到其他线程对指定变量的变更),成功的话就更新,失败则快速返回并再次尝试更新...
  然而分布式的情况下却容不得这种while(true)式的轻量级打法,
引用
You will find that the lock was not obtained after you already did
all the work to create the new value, issued and transfered the new
value, and so on...
一旦加锁失败,可以失败,但是你敢早点说失败吗?客户端把新的value送到服务端来供其CAS是很不容易的,尤其是在网络传输仍然是系统瓶颈的当今,最糟糕的是你一句话说失败了人家还要重来...你还不如让他在那挂起呢!
  还有一点,CAS比他的前辈悲观锁改善了很多,但是人品不好的线程被饿死的情况仍不能避免,然而至少一点,每个来抢锁的线程都是平等的,没有时延,但是分布式情况下就会彻底打破这种平衡,如果某台客户端机器因为质量问题而发送时延过大,那么他对服务端指定key里面的value的更新就永远别想提交了...
  至于redis拿什么方案来替代CAS的,我仍然在探索当中...但至少有一点,memcached不宜CAS

猜你喜欢

转载自invincibleliu.iteye.com/blog/1160662
今日推荐