如何释放主线程中的线程功能分配的内存 [英] How to free memory allocated by thread-function in the main

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

问题描述

我已经在线程函数 f1 中分配了 heap 内存,此存储用于计算堆区域中的值,以便主函数可以看到它./p>

这是线程函数定义:

  void * f1(void * input){int sum =(int *)malloc(sizeof(int));/*计算*/pthread_exit((void *)& sum);} 

在上面的代码中, sum 是堆分配的存储,其地址作为返回值传递到 main()<中的 sum1 /code>.

join main()中的线程是这样的:

  void * sum1;pthread_join(tid1,(void **)& sum1); 

一旦我检索到该值,我想释放所分配的内存.当我在主目录中使用 free 时,它会抱怨 munmap_chunk():无效指针

我怎样才能明确,安全地释放此内存?

解决方案

您应该发回指针,而不是其地址

  pthread_exit(sum);...pthread_join(tid1,& sum1); 

您要从线程函数发送回指针(使用 return pthread_exit())的指针.
pthread_join()中,您想要获取此指针,但是 pthread_join()的结果是一个整数,表示成功/失败.
然后,我们必须声明一个指针变量(此处为 sum1 )来存储预期结果,并为 pthread_join()提供此变量的地址,以便可以对其进行更新(我们以相同的方式为 scanf()提供地址,以更新提取的变量).

I have allocated heap memory in the thread function f1, this storage is used to calculate the value in the heap region so that the main function can see it.

Here is the thread function definition:

void *f1(void *input){


        int sum = (int*)malloc(sizeof(int));
        /* Do calculation */   
        pthread_exit((void*)&sum);
}

In the above code, the sum is the heap allocated storage, whose address is passed as a return value to the sum1 in the main().

I join the thread in the main() like this:

void *sum1;
pthread_join(tid1,(void**)&sum1);

Once i retrieved the value, i want to free the allocated memory. When i use free in the main, it complains like munmap_chunk(): invalid pointer

How can i explicitly and safely free this memory ?

解决方案

You should send back the pointer, not its address

pthread_exit(sum);
...
pthread_join(tid1, &sum1);

From the thread function you want to send back (with return or pthread_exit()) a pointer.
At pthread_join() you want to obtain this pointer but the result of pthread_join() is an integer to report success/failure.
Then we have to declare a pointer variable (sum1 here) to store the expected result and provide pthread_join() with the address of this variable so that it could be updated (the same way we provide addresses to scanf() in order to update the extracted variables).

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

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