C#内存分配无锁吗? [英] C# memory allocation lock free?

查看:84
本文介绍了C#内存分配无锁吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C ++库,现在将其移植到C#版本.我现在正在关注C#CLR中的内存分配.

I was working on C++ library and now I am porting it to C# version. I am now concerning about memory allocation in C# CLR.

该库将被多线程调用,所以我做了一个优化,而不是从需要lock()/unlock()的全局帮助中分配内存,而是使用了内存堆栈.这样可以避免线程争用.

This library will be called by multi-threads, so  I have done an optimization by instead of allocating memory from global help which requires lock()/unlock(), I used memory stack. This could avoid threads contention.

因此,转到C#.我听说内存分配非常快,因为一旦加载了CLR,GC就是预分配的内存池,但是线程争用如何? C#内存分配是否无锁?

So, moving to C#. I have heard that the memory allocation is very fast because GC is pre-allocated memory pool once CLR is loaded but how about threads contention? Does C# memory allocation lock free?

atanai

推荐答案

你好,

在.Net上,您处于托管代码中.这意味着您有垃圾回收.

on .Net, you are in Managed code. It's means you have garbage collection.

每次创建一个Value类型(int,double ...)时,它都会插入堆栈中.内存分配和删除速度非常快.

Each time you create an Value type (int, double ...), it's inserted in the stack. Memory very fast to allocation and removing.

每次创建引用类型(作为对象)时,它都会插入到.Net管理的堆中.

Each time you create a reference type (as an object) it's inserted in the heap managed by .Net.

该算法有点复杂,但要尽可能简单,它有3种区别(可分配内存的自由位置).

The algorithm is little bit complexe but to be simplest as possible, there are 3 générations (free places to allocate memory).

.Net可以看到合适的时机来处理垃圾内存时,将删除所有未使用的内存,并重新分配内存空间以允许下次快速分配内存.

When .Net could see a right moment to garbage memory, all unused memory is removed and memory space is rellocated to allow very fast allocation next time.

如果您想了解有关垃圾收集器的更多信息,可以阅读 垃圾收集的基础知识

If you want to know more informations about garbage collector, you could read Fundamentals of Garbage Collection

致谢

Cédric


这篇关于C#内存分配无锁吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆