I have been fighting with this for a loooong time. Looking around I don't seem to be able and find an answer. I simply create two detached threads and then use pthread_exit()
on both of them but there are leaks every now and then.
And because I know people will ask me:
- Yes, I have read all the other questions and there is no real answer
- I mark the threads as
detached
- I give
enough time
for the threads to initialize and die - I have read the manual for pthread_exit and it is used correctly
- It compiles fine with
-Wall
Code:
int threads_keepalive = 1;
void* thread_do(void *arg){
while(threads_keepalive)
sleep(1);
pthread_exit(NULL);
}
int main(){
/* Make threads */
pthread_t* threads;
threads = malloc(2 * sizeof(pthread_t));
pthread_create(&threads[0], NULL, thread_do, NULL);
pthread_create(&threads[1], NULL, thread_do, NULL);
pthread_detach(threads[0]);
pthread_detach(threads[1]);
sleep(1); // MAKING SURE THREADS HAVE INITIALIZED
/* Kill threads */
threads_keepalive = 0;
sleep(5); // MAKING SURE THREADS HAVE UNBLOCKED
free(threads);
return 0;
}
Running that code, although it is correct (at least in my eyes), I get memory leaks at random times. I run the same test multiple times with valgrind
as below
> gcc test.c -pthread -o test && for i in {1..100}; do valgrind --leak-check=full --track-origins=yes ./test 2>&1 | grep frees; done
==4088== total heap usage: 8 allocs, 4 frees, 2,230 bytes allocated
==4211== total heap usage: 8 allocs, 4 frees, 2,230 bytes allocated
==4337== total heap usage: 8 allocs, 4 frees, 2,230 bytes allocated
==4463== total heap usage: 8 allocs, 4 frees, 2,230 bytes allocated
==4590== total heap usage: 8 allocs, 8 frees, 2,230 bytes allocated
==4717== total heap usage: 8 allocs, 8 frees, 2,230 bytes allocated
==4853== total heap usage: 8 allocs, 4 frees, 2,230 bytes allocated
==4981== total heap usage: 8 allocs, 8 frees, 2,230 bytes allocated
==5110== total heap usage: 8 allocs, 8 frees, 2,230 bytes allocated
==5239== total heap usage: 8 allocs, 8 frees, 2,230 bytes allocated
..
What is going on??
Update: Creating one thread instead of two, doesn't show memory leaks.