How to use Multiple Variables for a lock Scope in C#

旧巷老猫 提交于 2019-12-21 09:53:11

问题


I have a situation where a block of code should be executed only if two locker objects are free.

I was hoping there would be something like:

lock(a,b)
{
    // this scope is in critical region
} 

However, there seems to be nothing like that. So does it mean the only way for doing this is:

lock(a)
{
    lock(b)
    {
        // this scope is in critical region
    }
}

Will this even work as expected? Although the code compiles, but I am not sure whether it would achieve what I am expecting it to.


回答1:


I'd expect it to, though there'd be a case where it could potentially cause a deadlock condition.

Normally, the code will attempt to lock a and then proceed to lock b if that succeeded. This means that it would only execute the code if it could lock both a and b. Which is what you want.

However, if some other code has already got a lock on b then this code will not do what you expect. You'd also need to ensure that everywhere you needed to lock on both a and b you attempt to get the locks in the same order. If you get b first and then a you would cause a deadlock.




回答2:


lock(a) lock(b) { // this scope is in critical region }

This could would block until the thread can acquire the lock for a. Then, with that lock acquired, it would block until the thread can acquire the lock for b. So this works as expected.

However, you have to be careful not to do this somewhere else:

lock(b) lock(a) { // this scope is in critical region }

This could lead to a deadlock situation in which thread 1 has acquired the lock for a and is waiting to acquire the lock for b, and thread 2 has acquired the lock for b and is waiting to acquire the lock for a.




回答3:


Requesting the lock on both should work fine. lock(a) will block until a is free. Once you have that lock, lock(b) will block until you have b. After that you have both.

One thing you need to be very careful about here is the order. If you're going to do this make sure you always get the lock on a before getting the lock on b. Otherwise you could very easily find yourself in a deadlock situation.



来源:https://stackoverflow.com/questions/2874028/how-to-use-multiple-variables-for-a-lock-scope-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!