在锁中使用非静态局部变量有什么意义?
有几次我遇到过这段代码,其中类中的局部变量(它不是静态变量)已在锁中使用。
public class SomeClass
{
private object obj = new object();
....
....
lock(obj)
{
}
}
考虑到它是实例变量,是否有任何锁定点?
A couple of times I have came across this code where a local variable in a class ( its NOT a static variable) has been used in a lock.
public class SomeClass
{
private object obj = new object();
....
....
lock(obj)
{
}
}
Is there any point of locking given that its an instance variables?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
多个线程可以作用于同一个实例,并且需要锁来保证线程安全。例如,考虑一个共享队列。
Multiple threads could be acting on the same instance and a lock is needed for thread-safety. Think, for example, of a shared queue.
静态锁对于控制对静态变量的访问很有用。实例锁对于控制对实例变量的访问很有用。
使用本地锁对象来保护本地变量(除非它是匿名函数或迭代器中捕获的外部变量)完全没有意义,因为其他线程将无法访问锁或变量。
A static lock would be useful for controlling access to a static variable. An instance lock would be useful for controlling access to an instance variable.
There is no point at all in using a local lock object to protect a local variable (unless it is a captured outer variable of an anonymous function or in an iterator), since other threads will not have access to either the lock or the variable.