问题描述
前端处理对特定大小的内存的请求。前端具有内存缓存,可用于分配或保存可用内存。该高速缓存一次只能由单个线程访问,因此它不需要任何锁,因此大多数分配和释放都是快速的。
这让我感到困惑,很显然我没有遵守。 tcmalloc如何假定一个线程分配的内存不会被其他线程访问。编写代码可以很容易地从一个线程分配内存,然后在另一个线程中释放它,如下所示。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
struct Book
{
int Pages;
};
volatile struct Book *pointer = NULL;
void *thread_function(void *index);
int main(int argc,const char *argv[])
{
pthread_t thread1,thread2;
int index1 = 1;
int index2 = 2;
char *message1 = "Thread 1";
char *message2 = "Thread 2";
pthread_create(&thread1,NULL,thread_function,(void *)(&index1));
pthread_create(&thread2,(void *)(&index2));
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
exit(0);
}
void *thread_function(void *index)
{
int res = *(int *)index;
if (res == 1)
{
pointer = malloc(sizeof(struct Book));
printf("Invoke malloc in thread 1,%p\n",pointer);
}
else if (res == 2)
{
while (1)
{
printf("check pointer in thread 2,pointer);
if (pointer != NULL)
{
printf("Invoke free in thread 2.\n");
free((struct Book *)pointer);
pointer = NULL;
break;
}
sleep(1);
}
}
}
使用以下命令编译它:gcc main1.c -o out1 -lpthread -ltcmalloc
并运行它:./out1
输出为:
Invoke malloc in thread 1,0x7f9b80000b60
check pointer in thread 2,0x7f9b80000b60
Invoke free in thread 2.
那么内存变量指针指向的位置是?我在线程1中分配了内存,然后在线程2中释放了内存。根据tcmalloc文档,分配的内存在线程1的线程本地缓存中。但是我在线程2中释放了内存。那么tcmalloc如何处理它。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)