分类: C/C++
2012-12-05 15:01:59
原文:http://wifihack.net/blog/2009/12/pthread-create-join-detach-release-thread/
这两天在看Pthread 资料的时候,无意中看到一句话(man pthread_detach):
也就是说:每个进程创建以后都应该调用pthread_join 或 pthread_detach 函数,只有这样在线程结束的时候资源(线程的描述信息和stack)才能被释放.
之后又查了 但是没有明确说明必须调用pthread_join 或 pthread_detach.
但是再查了 Pthread for win32
When a joinable thread terminates, its memory resources (thread descriptor and stack) are not deallocated until another thread performs pthread_join on it. Therefore, pthread_join must be called once for each joinable thread created to avoid memory leaks.
#include#include#includevoid *PrintHello(void){pthread_detach(pthread_self());int stack[1024 * 20] = {0,};//sleep(1);long tid = 0;//printf(“Hello World! It’s me, thread #%ld!\n”, tid);//pthread_exit(NULL);}int main (int argc, char *argv[]){pthread_t pid;int rc;long t;while (1) {printf(“In main: creating thread %ld\n”, t);rc = pthread_create(&pid, NULL, PrintHello, NULL);if (rc){printf(“ERROR; return code from pthread_create() is %d\n”, rc);//exit(-1);}sleep(1);}printf(” \n— main End —- \n”);pthread_exit(NULL);}
#include#include#includevoid *PrintHello(void){int stack[1024 * 20] = {0,};//pthread_exit(NULL);//pthread_detach(pthread_self());}int main (int argc, char *argv[]){pthread_t pid;int rc;long t;while (1) {printf(“In main: creating thread %ld\n”, t);pthread_attr_t attr;pthread_t thread;pthread_attr_init (&attr);pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);rc = pthread_create(&pid, &attr, PrintHello, NULL);pthread_attr_destroy (&attr);if (rc){printf(“ERROR; return code from pthread_create() is %d\n”, rc);//exit(-1);}sleep(1);}printf(” \n— main End —- \n”);pthread_exit(NULL);}
#include#include#includevoid *PrintHello(void){int stack[1024 * 20] = {0,};//sleep(1);long tid = 0;//pthread_exit(NULL);//pthread_detach(pthread_self());}int main (int argc, char *argv[]){pthread_t pid;int rc;long t;while (1) {printf(“In main: creating thread %ld\n”, t);rc = pthread_create(&pid, NULL, PrintHello, NULL);if (rc){printf(“ERROR; return code from pthread_create() is %d\n”, rc);//exit(-1);}pthread_join(pid, NULL);sleep(1);}printf(” \n— main End —- \n”);pthread_exit(NULL);}