我在 C# 中有一个多线程进程,每个线程都经常尝试从堆中分配内存。这需要多个堆的锁,因此减少了线程的优势。
是否有线程的本地堆之类的东西,以便同时尝试从不同线程分配内存不会锁定其中一个线程?
最佳答案
根据 this article ,当多个线程并发分配内存时,在多处理器系统中没有争用:
Synchronization-free Allocations On a multiprocessor system, generation 0 of the managed heap is split into multiple memory arenas using one arena per thread. This allows multiple threads to make allocations simultaneously so that exclusive access to the heap is not required.
编辑:Hans Passant 正确地指出,为了应用此行为,必须在工作站环境中强制垃圾收集器进入 gcServer
模式。
这是通过编辑 app.config
或 web.config
文件并确保定义以下设置来完成的:
<configuration>
<runtime>
<gcServer enabled="true"/>
</runtime>
...
</configuration>
关于多线程进程中线程的 C# 本地堆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17118098/