并发编程使用锁的代价

锁提供了相互排斥,并确保变化的可见性以一种有序的方式发生。锁是非常昂贵的,因为它们在争夺时需要仲裁。这种仲裁(获取锁)是通过向操作系统内核的上下文切换来实现的,它将暂停在锁上等待的线程,直到它被释放。在这样的上下文切换(获取锁)过程中,以及向操作系统释放控制权的过程中,执行上下文可能会丢失之前缓存的数据和指令,而操作系统可能会决定在它拥有控制权的时候做其他的内部管理任务。这对现代处理器的性能会产生严重的影响。虽然可以采用快速的用户模式锁,但是这些锁只有在不被争夺的情况下才会有真正的好处。

我们将通过一个简单的演示来说明锁的代价。这个实验的重点是调用一个函数,在一个循环中增加一个64位的计数器5亿次。如果用Java编写,这可以在2.4Ghz的英特尔Westmere EP上由一个单线程执行,只需300ms。语言对这个实验并不重要,在所有具有相同基本原语的语言中,结果都是相似的。

一旦引入锁以提供相互排斥,即使锁尚未被争夺,成本也会大幅上升。当两个或更多的线程开始争夺时,成本再次增加,而且是以数量级增加的。这个简单实验的结果显示在下面的表格中。

Method

Time (ms)

Single thread

300

Single thread with lock

10,000

Two threads with lock

224,000

Single thread with CAS

5,700

Two threads with CAS

30,000

Single thread with volatile write

4,700

Locks provide mutual exclusion and ensure that the visibility of change occurs in an ordered manner. Locks are incredibly expensive because they require arbitration when contended. This arbitration is achieved by a context switch to the operating system kernel which will suspend threads waiting on a lock until it is released. During such a context switch, as well as releasing control to the operating system which may decide to do other house-keeping tasks while it has control, execution context can lose previously cached data and instructions. This can have a serious performance impact on modern processors. Fast user mode locks can be employed but these are only of any real benefit when not contended.

We will illustrate the cost of locks with a simple demonstration. The focus of this experiment is to call a function which increments a 64-bit counter in a loop 500 million times. This can be executed by a single thread on a 2.4Ghz Intel Westmere EP in just 300ms if written in Java. The language is unimportant to this experiment and results will be similar across all languages with the same basic primitives.

Once a lock is introduced to provide mutual exclusion, even when the lock is as yet un-contended, the cost goes up significantly. The cost increases again, by orders of magnitude, when two or more threads begin to contend. The results of this simple experiment are shown in the table below:

Method

Time (ms)

Single thread

300

Single thread with lock

10,000

Two threads with lock

224,000

Single thread with CAS

5,700

Two threads with CAS

30,000

Single thread with volatile write

4,700

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值