【发布时间】:2020-10-15 01:52:20
【问题描述】:
我在读一本教科书,上面写着:
int pthread_join(pthread_t tid, void **thread_return);
pthread_join 函数阻塞直到线程 tid 终止,将线程例程返回的通用
(void *)指针分配给 thread_return 指向的位置,然后获取终止线程持有的所有内存资源。
我对终止线程持有的内存资源有点困惑,听起来 pthread_join 会隐式调用free 以释放终止线程中的堆内存,但显然事实并非如此,例如:
void *thread(void *arg) {
char *ret;
if ((ret = (char*) malloc(20)) == NULL) { //<------------allocated heap memory
perror("malloc() error");
exit(2);
}
strcpy(ret, "This is a test");
pthread_exit(ret);
}
main() {
pthread_t thid;
void *ret;
if (pthread_create(&thid, NULL, thread, NULL) != 0) {
perror("pthread_create() error");
exit(1);
}
if (pthread_join(thid, &ret) != 0) {
perror("pthread_create() error");
exit(3);
}
printf("thread exited with '%s'\n", ret);
}
pthread_join 被调用后,ret 仍然指向分配的堆内存,可以打印字符串。所以对等线程中分配的堆内存没有释放。
那么被终止的线程持有的什么样的内存资源会被回收呢?
【问题讨论】:
-
我认为它只是指用于表示线程的内存,而不是线程代码使用的内存。
-
线程的任何“线程本地存储”也将被释放。
标签: c multithreading pthreads