Should I put large arrays on stack or heap?

I'm developing a multi-threaded application in C. I'm currently playing with 40 threads and each uses an array of around 2Mb.

I'm currently allocating this array dynamically, so I do:

char *data = malloc(2097152 * sizeof(char));

These threads are serving requests, so this array is constantly allocated and free'd, each time a new request comes in.

All is working fine, but I'm using valgrind's massif tool and it shows me that I have at times an 80Mb heap. So I'm kind of wondering, will I have heap fragmentation problems? I also allocate smaller chunks of memory on other places of my code.

Also, would I benefit from having an static array? I'm looking of ways to improve my performance and I wonder if this would help. However, I'm afraid of doing that and ending up with a stack overflow. 80Mb in the stack seems too large...

Any advice? I really don't know what size of heap/stack is too big.


You seem to be heading in this direction anyway, but there are some design patterns that you could be using to assist you in this.

firstly memory pooling http://www.codeproject.com/Articles/27487/Why-to-use-memory-pool-and-how-to-implement-it This can be used to remove the overhead of allocating and de-allocating the memory.

second I am going to assume that you are creating threads as well for the sake of completeness

so thread pooling, if you have a pool of threads that access a pool of memory you should be sorted. http://en.wikipedia.org/wiki/Thread_pool_pattern

Hopefully this gives you some help on ideas on how you can go solve your issue.

链接地址: http://www.djcxy.com/p/13906.html

上一篇: 如果共享,OpenMP会将堆栈或数据变量移动到堆上吗?

下一篇: 我应该把大数组放在堆栈还是堆?