c - 从多个线程返回动态分配的 char 数组并在 c 中释放 main 内的内存
问题描述
我创建了一个线程数组,并根据 isSetFunc() 中的某些条件更改了全局变量。在返回动态分配的字符数组并将其打印在 main 中时,它仅在 main 函数中打印最后一个线程结果,并且在取消分配在线程内创建的 main 函数内的内存时,没有被取消分配。
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#define BUFFER 10
int gset;
int gnot_set;
pthread_mutex_t glock;
void *SetFunc(void *args){
char* string = (char *)calloc(BUFFER, sizeof(char));
int* arg = (int *) args;
pthread_mutex_lock(&glock);
if(*arg < 4){
gset++;
strcpy(string, "True\n");
}
else{
gnot_set++;
strcpy(string, "False");
}
pthread_mutex_unlock(&glock);
return string;
}
int main()
{
int threadRes,
i = 0;
void* pResult;
pthread_t* thread;
pthread_mutex_init(&glock, NULL);
thread = (pthread_t *)malloc(sizeof(pthread_t)*(10));
while (i < 10)
{
threadRes = pthread_create(&(thread[i]), NULL, &isSetFunc, &i);
if(threadRes != 0){
fprintf(stderr, "Error occured while creating a thread\n");
return -1;
}
pthread_join(thread[i], &pResult);
i++;
}
printf("In main thread: %s\n", (char *)pResult);
printf("\ng_set = %d\ngnot_set = %d\n", gset, gnot_set);
pthread_mutex_destroy(&glock);
free(thread);
free(pResult);
return 0;
}
输出
==387== Memcheck, a memory error detector
==387== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==387== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==387== Command: ./a.out
==387==
==387== error calling PR_SET_PTRACER, vgdb might block
In main thread: False
g_set = 4
gnot_set = 4
==387==
==387== HEAP SUMMARY:
==387== in use at exit: 70 bytes in 7 blocks
==387== total heap usage: 11 allocs, 4 frees, 4,512 bytes allocated
==387==
==387== LEAK SUMMARY:
==387== definitely lost: 70 bytes in 7 blocks
==387== indirectly lost: 0 bytes in 0 blocks
==387== possibly lost: 0 bytes in 0 blocks
==387== still reachable: 0 bytes in 0 blocks
==387== suppressed: 0 bytes in 0 blocks
==387== Rerun with --leak-check=full to see details of leaked memory
==387==
==387== For lists of detected and suppressed errors, rerun with: -s
==387== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
任何帮助将不胜感激和感谢。
解决方案
您的线程一次运行一个,因此您只在所有线程运行后打印最终结果。
该pthread_join
函数使调用线程等待,直到指定的线程返回。由于您在pthread_join
之后调用pthread_create
,这意味着您创建一个线程,等待它完成,然后创建一个新线程,等等。
您看到的内存泄漏是因为每个线程都返回分配的内存,但您只在程序结束时释放它一次,所以您只释放最后一个线程的结果。
您需要两个循环:一个用于创建线程,一个用于连接它们。第二个循环应该调用pthread_join
,锁定互斥量,打印值,解锁,然后free
返回值。
推荐阅读
- ethereum - 在 Solidity 中检查和授予角色
- wordpress - 为什么响应式设计不适用于 elementor?
- css - 不要将背景拉伸到伪元素之前
- ubuntu - JBoss应用服务器7适配Red Hat
- java - 有没有办法在 spring (gradle) 中隐藏我的 BD 密码和用户名
- angular - Angular Firebase createUserWithEmailAndPassword 添加附加字段
- python - 添加自定义测试结果(日志)以在 pytest-html 中报告
- c# - 要求 System.Text.Json.Serialization 不为对象转换字段
- python-3.x - Pymupdf 的 draw_rect 方法不适用于某些 pdf 页面
- python - 如何在 python 日志记录模块的 FileHandler 中设置行缓冲?