与每个对象关联的临界区是如何初始化的?

发布于 2024-12-22 11:05:11 字数 145 浏览 3 评论 0原文

当你说

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

友谊不毕业 2024-12-29 11:05:11

每个对象都会分配一个 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.

愚人国度 2024-12-29 11:05:11

根据 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文