SpinLock.Enter如何无法获取锁? [英] How can SpinLock.Enter fail to acquire the lock?

查看:89
本文介绍了SpinLock.Enter如何无法获取锁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自旋锁结构可用于管理从多个线程对资源的访问.除了普通锁以外,它还使用繁忙的等待,如果预期的等待时间很短(但会占用更多资源),则等待会更快.

The SpinLock structure in .Net can be used to manage access to resources from multiple threads. Other than a normal lock it uses a busy waiting, which is faster if the expected wait time is very low (but consumes more resources).

其他线程原语(例如Monitorlock(...){})始终获取锁(或永远等待获取锁).但是SpinLock.Enter方法使用ref bool参数来指示是否获取锁定失败.

Other threading primitives such as a Monitor and lock(...){} always acquire the lock (or wait forever to acquire it). But the SpinLock.Enter method uses a ref bool parameters to indicate wether or not acquiring the lock failed.

需要什么ref bool lockTaken?在什么情况下Monitor.Enter可能会失败(并因此将lockTaken设置为false?)

What is the ref bool lockTaken needed and in what cases can Monitor.Enter fail (and thus set lockTaken to false?)

推荐答案

使用此"lockTaken"模式是为了确保线程同步结构确实采用了这种锁定.问题是-Monitor和SpinLock在finally块内部退出,而在try块中进行了锁定.

This 'lockTaken' pattern is used in order to be sure about that lock is really taken by thread sync construct. Thing is - Monitor and SpinLock internally exit in finally block and lock is taken in try block.

现在,如果线程已进入try块并在被锁定之前被中止,则不应在finally块中将其释放.该问题通过ref bool变量解决.

Now, if thread has entered try block and was aborted before it was taken lock then it shouldn't be released in finally block. That problem is solved via ref bool variable.

Boolean taken = false;
try {
    // An exception (such as ThreadAbortException) could occur here...
    Monitor.Enter(this, ref taken);
}
finally {
    if (taken) Monitor.Exit(this);
}

这篇关于SpinLock.Enter如何无法获取锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆