选择正确的对象来锁定线程同步?
通常代码示例以这种方式使用锁:
static readonly object lockForWorkingWithSharedObject = new object();
lock(lockForWorkingWithSharedObject)
{
// do something with shared object
}
这样我们就需要在一个大类中使用许多锁。 使用共享对象本身作为同步对象是个好习惯吗?
// of course here sharedObject is a reference type
lock(sharedObject)
{
// do something with sharedObject
}
Generally code samples use locks this way:
static readonly object lockForWorkingWithSharedObject = new object();
lock(lockForWorkingWithSharedObject)
{
// do something with shared object
}
This way we need many locks in a large class.
Is it good practice to use the shared object itself as the synchronization object ?
// of course here sharedObject is a reference type
lock(sharedObject)
{
// do something with sharedObject
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 Java 和 .NET 中,让每个对象都可锁定的目的正是因为语言设计者认为使用对象本身作为锁会很有用;因此,Java 中也有
synchronized
关键字。如果您需要更精细的锁定粒度,我会假设您最好将对象的状态拆分为多个对象,并按语义上属于在一起的事物进行分组,因此可能还需要防止并发访问。
In Java and .NET, the point of having each object lockable is precisely because language designers thought it would be useful to use the object itself as the lock; hence also the
synchronized
keyword in Java.If you need much finer granularity of locking, I would assume that you better split the state of your object in multiple objects, grouped by things that semantically belong together, and thus likely also need to protected against concurrent access together.