我读到了 pthread_detach ,它在调用线程时释放了线程获取的资源,所以我做了一个小实验,但即使在分离线程之后,看起来资源也没有释放。这是代码:
#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;
}