gpt4 book ai didi

c - 每线程内存分配

转载 作者:太空狗 更新时间:2023-10-29 15:56:28 29 4
gpt4 key购买 nike

我正在为多线程应用程序开发一个跟踪工具,尤其是关于内存分配的。

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

我在 malloc 上做了一个包装,每次有 malloc 时递增值:

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

效果很好。问题在于 free 方法,它不返回释放了多少内存。

不要考虑我的解决方案,它只是为了展示我的尝试。

编辑:

如上所述,保留我自己的表是一种过于繁重的方法。

最佳答案

如何改变 mymalloc 来做:

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

然后,在 myfree(void* mem) 中,您:

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);
}

这可以优化,但我希望你能理解...

关于c - 每线程内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/781118/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com