使用现有对象而不是创建特定的锁对象安全吗?
编辑:事实证明,当我浏览时,我发现了一个问题,它似乎与我之前没有找到的问题相同: lock(locker) 和 lock(variable_which_I_am_using) 之间的区别
我正在查看一些代码并试图弄清楚我的想法锁定的东西,我想我已经到达那里了。
现在我注意到在一些代码中我正在检查一个对象是这样创建的:
private HashSet<Graphic> clustersInUse = new HashSet<Graphic>();
然后在代码中进一步使用如下:
lock (clustersInUse)
{
// Do something with the Hashset
}
现在,这样做而不是为锁创建特定对象是否存在问题。像这样:
private object clusterLocker = new object();
如果上面的 clustersInUse 以某种方式放入公共属性中,会发生什么?
另外,如果有东西试图访问 clustersInUse 而不锁定它,而它被锁定在另一个线程中,那么会发生什么?
EDIT: As it turns out when I was browsing I found a question the appears to be the same as mine which I didn't find earlier: Difference between lock(locker) and lock(variable_which_I_am_using)
I am looking at some code and trying to get my head around the locking thing and I am getting there I think.
Now I noticed in some code I am reviewing that an object is created like so:
private HashSet<Graphic> clustersInUse = new HashSet<Graphic>();
Then further in the code is used like so:
lock (clustersInUse)
{
// Do something with the Hashset
}
Now, is there a problem doing this rather than creating a specific object for the lock. Like this:
private object clusterLocker = new object();
What happens if the clustersInUse
above somehow gets put into a public property, what happens then?
Also, if something tries to access the clustersInUse
without locking it whilst it is locked in another thread what would happen then?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一般规则是您希望控制锁定对象的范围,以防止某些未知代码导致意外行为。在这种情况下,您使用的是私有实例变量,因此只要您不分发对它的引用,就可能没问题。
如果您正在分发引用并锁定它,而其他代码正在锁定这些引用(例如,修改集合时),则更改行为很容易引入线程错误。
如果有人将其放入公共财产中,如果他们锁定了该财产,则该财产被视为“分发引用”,您对锁定的调用将被阻塞,直到他们解锁为止。这是否可取取决于他们对收藏的用途。
锁定对象不会影响将该对象用于同步以外的任何目的。
The general rule is that you want to control the scope of the object your locking on to prevent some unknown code from causing unexpected behavior. In this case you are using a private instance variable so you are probably OK as long as you are not handing out references to it.
If you are handing out references and locking on it and other code is locking those references (e.g. when modifying the collection) changing the behavior could easily introduce threading bugs.
If someone puts it into a public property that counts as "handing out references" if they lock on it your call to lock will block until they unlock it. Whether this is desirable or not depends on what they are doing with the collection.
Having the object locked will have have no effect on using the object for any purpose other than synchronization.
你几乎已经回答了你自己的问题。对于锁定,通常最好专门为此目的创建一个对象,并且通常私有地由表达高层同步逻辑的访问器方法使用。
You've pretty much answered your own question. For locking, it's generally better to create an object specifically for the purpose, and usually held privately for use by accessor methods that express synchronisation logic at a high level.