[英]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.