与每个对象关联的临界区是如何初始化的?
当你说
lock (obj)
...
.NET使用obj
中的临界区来同步以下语句时。
这个临界区是如何初始化的? (例如,它是在构造时初始化还是延迟初始化?)
When you say
lock (obj)
...
.NET uses the critical section in obj
to synchronize the following statements.
How is this critical section initialized? (e.g. is it initialized at construction time, or lazily?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
每个对象都会分配一个 4 字节的内存“块”(syncblk),它是 SyncTableEntry 的索引。创建对象时,syncblk 被分配为 0,这可以防止任何额外的内存分配(除了这个 4 字节数之外)。当获得锁定时,该syncblk被设置为表中的适当条目,这随后可能导致分配。实际上,这是一个延迟初始化。
当您调用 lock(object) 时,这实际上是在对象上使用
Monitor.Enter
,从而相应地设置条目。有关详细信息,请参阅这篇有关 .NET 内存内部结构的 MSDN 文章。Every object gets a 4 byte "block" of memory allocated to it (the syncblk) that is an index into a SyncTableEntry. When the object is created, the syncblk is assigned 0, which prevents any extra memory allocation (other than this 4 byte number). When a lock is taken, this syncblk is set to the appropriate entry in the table, which may then cause an allocation. In effect, it's a lazy initialization.
When you call lock(object), this is effectively using
Monitor.Enter
on the object, which in turn sets the entry appropriately. For details, see this MSDN article on .NET Memory Internals.根据 Microsoft 的文档,当声明 CRITICAL_SECTION 类型的变量时,进程会分配临界区的内存。
According to Microsoft's documentation the process allocates the memory of a critical section when a variable of type CRITICAL_SECTION is declared.