Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Local heaps for threads in multithread process

I have a multithread process in C#, and every thread quite often tries to allocate memory from the heap. This entails in multiple heap's locks and therefore reduces advantage from threading.

Is there something like local heaps for threads, so that simultaneous attempt to allocate memory from different threads wouldn't lock one of them?

like image 722
Kamil Avatar asked Jun 29 '26 16:06

Kamil


1 Answers

According to this article, there is no contention in a multiprocessor system when multiple threads allocate memory concurrently:

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.

EDIT: Hans Passant has correctly pointed out that in order for this behavior to apply, the garbage collector must be forced to gcServer mode in a workstation environment. This is done by editing either the app.config or web.config file, and ensuring the following setting is defined:

<configuration> 
    <runtime> 
        <gcServer enabled="true"/> 
    </runtime> 
    ...
</configuration> 

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!