[英]pThreads how to terminate a thread in c without memory leaks
我想知道如何正确终止线程而不产生任何 memory 泄漏。
我创建了一个更直接的程序来演示我的问题。 在下面的代码中,我在 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 one\n");
return NULL;
}
运行程序时,它会打印出“thread one”,然后要求用户输入。 如果用户输入 EXIT,它将终止线程,而其他任何东西都会加入线程。 运行 Valgrind 时,我得到以下结果:
输入 - 退出
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
输入 - 测试
==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_CANCELED 作为线程的退出状态。 (加入线程是知道取消已完成的唯一方法。)
首先,如果pthread_cancel
只是从系统中完全清除线程的所有痕迹,则绝对没有办法实施此规定。 其次, pthread_cancel
可能会也可能不会立即取消线程。 它发送取消请求。 是否尊重它,或何时尊重它取决于线程。 您不能假设线程在pthread_cancel
返回后立即被取消。 一个正在运行的线程自然会消耗一些资源。 如果您在pthread_cancel
之后但在线程实际取消之前exit
, valgring
将愉快地报告丢失 memory。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.