Will pthread_detach manage my memory for me?
-
02-07-2019 - |
Question
Suppose I have the following code:
while(TRUE) {
pthread_t *thread = (pthread_t *) malloc(sizeof(pthread_t));
pthread_create(thread, NULL, someFunction, someArgument);
pthread_detach(*thread);
sleep(10);
}
Will the detached thread free the memory allocated by malloc, or is that something I now have to do?
Solution
No. pthread_create() has no way of knowing that the thread pointer passed to it was dynamically allocated. pthreads doesn't use this value internally; it simply returns the new thread id to the caller. You don't need to dynamically allocate that value; you can pass the address of a local variable instead:
pthread_t thread;
pthread_create(&thread, NULL, someFunction, someArgument);
OTHER TIPS
You need to free the memory yourself. It would be preferable to simply allocate the pthread_t variable on the stack as opposed to the heap.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow