I read about pthread_detach that it releases the resources acquired by thread when it is called so I did a little experiment but even after detaching the thread, it looks like it resources are not released. Here is the code:
#define SIZE 2048
void *func(void *arg);
int main()
{
void *x;
int i;
pthread_t tid;
pthread_attr_t attr,attr2;
int fp=open("SharedMemWithMutex.c",O_RDONLY);
pthread_attr_init(&attr2);
pthread_create(&tid,&attr2,func,&fp);
pthread_join(tid,&x);
i=*(int *)x;
fprintf(stderr,"BEFORE DETACH: read bytes are %d\n",i);
pthread_detach(tid);
i=*(int *)x;
fprintf(stderr,"AFTER DETACH: read bytes are %d\n",i);
return 0;
}
void *func(void *arg)
{
int fp=*(int *)arg;
char buf[SIZE];
int *readbytes=(int *) malloc(sizeof(int));
*readbytes=read(fp,buf,SIZE);
return readbytes;
}
Here “resources” only includes internal
pthreadsresources that are needed to join the thread and find out its exit status.It does not cover any other resources that you acquire yourself (heap memory, open files, database connections, etc). It may be helpful to realize that such resources don’t generally have an intrinsic notion of belonging to a particular thread, since threads can freely share them.
There a several other issues with your code:
pthread_detach()is probably returning an error code.i=*(int *)x. Even ifreadbytesdid get automatically deallocated, the secondi=*(int *)xwould simply result in undefined behaviour, which may or may not have manifested itself in any particular way.