私は簡単なスレッドプログラムを書きました:
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdint.h>
#define THREADS 5
void* HelloWorld(void *t)
{
printf("Thread ID #%lu: (%lu) Hello World !!\n", pthread_self(), (unsigned long)t);
return NULL;
}
int main()
{
pthread_t thread[THREADS];
uint32_t i;
int err;
for(i = 0; i < THREADS; ++i)
{
err = pthread_create(&thread[i], NULL, &HelloWorld, (void*)(unsigned long long)i);
if(err != 0)
{
printf("Error %d: Thread %d Creation Unsuccessful !!\n", err, i);
}
printf("Thread %lu in main()\n", pthread_self());
}
/*
for(i = 0; i < THREADS; ++i)
{
pthread_join(thread[i], NULL); // Error checking implemented
}
*/
return 0;
}
ただし、valgrindを次のように使用する場合:
valgrind --tool=memcheck --leak-check=full --show-reachable=yes ./hello
pthread_join()
プログラムで使用されているかどうかに関係なく、メモリ使用量/リークについて同じ出力が表示されます。
ここで読んだように、この動作を説明してください:
pthread_join() または pthread_detach() 関数は、スレッドに関連付けられたストレージを再利用できるように、detachstate 属性を PTHREAD_CREATE_JOINABLE に設定して作成されたすべてのスレッドに対して最終的に呼び出す必要があります。
呼び出さない場合のストレージの再利用方法pthread_join()