切断されていない pthread を実行しているプロセスを終了すると、既知のメモリ リークが発生します。ただし、スレッドを切り離すことは解決策ではないようです。次の最小限の例を考えてみましょう。
#include <pthread.h>
#include <stdio.h>
static void* thread(void* _) {
for(;;); return NULL;
}
int main(void) {
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_t tid; pthread_create(&tid, &attr, thread, NULL);
pthread_attr_destroy(&attr);
return 0;
}
無限ループを持つ切り離されたスレッドが作成され、プロセスはすぐに終了します。によるとpthread_detach(3)
、プロセス全体が終了すると、スレッドのリソースは自動的にシステムに解放されます。ただし、それは明らかに起こっていることではありません。
gcc -pthread c.c
valgrind --leak-check=full a.out
==9341== Command: a.out
==9341==
==9341==
==9341== HEAP SUMMARY:
==9341== in use at exit: 272 bytes in 1 blocks
==9341== total heap usage: 1 allocs, 0 frees, 272 bytes allocated
==9341==
==9341== 272 bytes in 1 blocks are possibly lost in loss record 1 of 1
==9341== at 0x4C2ABB4: calloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==9341== by 0x4012598: _dl_allocate_tls (dl-tls.c:296)
==9341== by 0x4E3C7B5: pthread_create@@GLIBC_2.2.5 (allocatestack.c:579)
==9341== by 0x400825: main (in /home/witiko/a.out)
==9341==
==9341== LEAK SUMMARY:
==9341== definitely lost: 0 bytes in 0 blocks
==9341== indirectly lost: 0 bytes in 0 blocks
==9341== possibly lost: 272 bytes in 1 blocks
==9341== still reachable: 0 bytes in 0 blocks
==9341== suppressed: 0 bytes in 0 blocks
私は心配する必要がありますか?実際のプログラムにはいくつかのブロッキング スレッドがあるため、最小限の例と同様に、それらを実際に使用することはできませんpthread_join()
。直接 ing するpthread_cancel()
のではなく、電話する必要がありますか?exit()