每个线程的内存分配 [英] Per thread memory allocation

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

问题描述

我工作了多线程应用,更特别的是关于内存分配跟踪工具。

I am working on a trace tool for multithread applications, more especially about memory allocation.

我想每个线程的内存分配。我知道,当一个线程做一个malloc,使用的内存全局堆中。我想跟踪的线程分配多少内存。

I would like a per thread memory allocation. I know that when a thread do a malloc, the memory used is the global heap. I would like to trace which thread allocated how much memory.

我做的malloc时的包装,每次有一个malloc为递增值:

I did a wrapper upon malloc, incrementing values each time there is a malloc as:

void *mymalloc(size_t size) {
    mem_used[thread_id] += size;
    return malloc(size);
}

它运作良好。问题是与免费方法,该方法不返回多少内存被释放。

It works well. The problem is with free method, which does not return how much memory is released.

不要顾及我的解决方案,它只是展示一下我试过了。

Don't take into account my solution, it is just to show what I tried.

编辑:

如上mentionned,保持我自己的表是一个过于沉重的方法。

As mentionned above, keeping my own table is a too heavy method.

推荐答案

怎么样改变mymalloc做:

how about changing mymalloc to do:

int* mymem = malloc(size + sizeof(int)*2);
mymem[0] = thread_id;
mymem[1] = size;
mem_used[thread_id] += size;
return &mymem[2].

然后,在myfree(无效* MEM),您可以:

Then, in myfree(void* mem), you:

void myfree(void* mem)
{
    int* imem = (int*)(mem - sizeof(int)*2);
    int thread_id = imem[0];
    int size = imem[1];
    mem_used[thread_id] -= size;
    free(imem);
}

这可以优化,但我希望你的想法......

this can be optimized, but I hope you get the idea...

这篇关于每个线程的内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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