pThreads如何在没有内存泄漏的情况下终止c中的线程



我想知道如何在不产生任何内存泄漏的情况下正确地终止线程。

我创建了一个更直接的程序来演示我的问题。在下面的代码中,我在main中创建了一个父线程,父线程创建了六个线程,但是对于本例,为了简单起见,我只完成了一个线程。父线程将请求用户输入,如果是EXIT,则需要终止所有子线程。否则,如果是其他情况,它将继续处理并在最后加入。本例的线程打印出一个字符串,然后返回。

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
void *ParentThread(void * args);
void *oneThread(void *args);
void *twoThread(void *args);
int main(int argc, char const *argv[])
{

/* Declare parent thread */
pthread_t parent;
/* Create parent thread */
pthread_create(&parent, NULL, ParentThread, NULL);
pthread_join(parent, NULL);
return 0;
}
void *ParentThread(void * args)
{
char sUserInput[10];
pthread_t A;
pthread_create(&A, NULL, oneThread, NULL);
scanf("%10s", sUserInput);
/* Check if input is 'EXIT' */
if(strcmp(sUserInput, "EXIT") == 0)
{   
/* Terminate Threads */
pthread_cancel(A);
}
else
{
/*
Other actions are performed 
*/
pthread_join(A, NULL);
}
return NULL;
}
void *oneThread(void *args)
{
/* just an example to see if the thread is working */
printf("thread onen");
return NULL;
}

运行程序时,将打印出"线程1";然后为用户请求输入。如果用户输入EXIT,它将终止线程,而其他线程将加入线程。当运行Valgrind时,我得到以下结果:

Input - EXIT

HEAP SUMMARY:
==217==     in use at exit: 272 bytes in 1 blocks
==217==   total heap usage: 4 allocs, 3 frees, 8,736 bytes allocated
==217==
==217== LEAK SUMMARY:
==217==    definitely lost: 0 bytes in 0 blocks
==217==    indirectly lost: 0 bytes in 0 blocks
==217==      possibly lost: 272 bytes in 1 blocks
==217==    still reachable: 0 bytes in 0 blocks
==217==         suppressed: 0 bytes in 0 blocks
enter code here

Input - Test

==220== HEAP SUMMARY:
==220==     in use at exit: 0 bytes in 0 blocks
==220==   total heap usage: 4 allocs, 4 frees, 8,736 bytes allocated
==220==
==220== All heap blocks were freed -- no leaks are possible 

如果您需要更多的信息或澄清,请告诉我

线程取消不会释放其资源:

源自man pthread_create

线程可以是可接合的,也可以是分离的。如果线程是然后另一个线程可以调用pthread_join(3)来等待用于线程终止并获取其退出状态。只有当已连接的终止可连接线程是其最后一个可连接线程释放回系统的资源当一个分离的线程终止时,其资源被自动释放回系统:不可能为了加入线程而加入获取退出状态

所以,只需调用pthread_join或取消线程以获得其资源,并使valgrind高兴。


另一个解决方案是将其分离。

应该调用pthread_join(3)或pthread_detach()应用程序创建的每个线程,以便系统资源. (但请注意,资源任何未执行这些操作的线程都将被删除当进程终止时被释放

即使你取消了一个线程,你仍然需要加入它,以释放与它相关的所有资源。

被取消的线程终止后,与该线程连接使用pthread_join(3)获取pthread_cancelled作为线程的退出状态。(与线程连接是了解这一点的唯一方法取消已完成。)

首先,如果pthread_cancel只是从系统中完全擦除线程的所有痕迹,则绝对没有办法实现此规定。其次,pthread_cancel可能立即取消线程,也可能不立即取消线程。它发送一个取消请求。这取决于线程是否尊重它,或者何时尊重它。您不能假设在pthread_cancel返回后线程立即被取消。运行的线程自然会消耗一些资源。如果exitpthread_cancel之后,但在线程实际取消之前,valgring将高兴地报告内存丢失。

最新更新