酒类公司网站模板,公司名称大全好听,代理注册公司注意什么,高校档案网站建设的目的是什么意思pthread_exit#xff1a;
在线程中禁止调用exit函数#xff0c;否则会导致整个进程退出#xff0c;取而代之的是调用pthread_exit函数#xff0c;这个函数只会使一个线程退出#xff0c;如果主线程使用pthread_exit函数也不会使整个进程退出#xff0c;不会影响其他线程…pthread_exit
在线程中禁止调用exit函数否则会导致整个进程退出取而代之的是调用pthread_exit函数这个函数只会使一个线程退出如果主线程使用pthread_exit函数也不会使整个进程退出不会影响其他线程的执行
函数原型void pthread_exit(void *retval);
函数参数retval通常传NULL
注意pthread_exit或者return返回的指针所指向的内存单元必须是全局的或者使用nalloc分配的不能在线程函数的栈上分配因为当其他线程得到这个返回指针时这个线程函数已经退出了栈空间会被回收
通过以下代码我们可以发现子线程执行exit会让整个进程结束。
#includestdio.h
#includestdlib.h
#includestring.h
#includesys/types.h
#includeunistd.h
#include pthread.h
void *mythread(void *arg)
{printf(child thread,pid[%d],id[%ld]\n,getpid(),pthread_self());exit(0);
}
int main()
{//int pthread_create(pthread_t *thread, const pthread_attr_t *attr,// void *(*start_routine) (void *), void *arg);pthread_t thread;int retpthread_create(thread,NULL,mythread,NULL);if(ret!0){printf(pthread_create error:[%s]\n,strerror(ret));return -1;}sleep(1);//让子线程先执行printf(father thread,pid[%d],id[%ld]\n,getpid(),pthread_self());
} 可以发现主线程并没有执行
通过以下代码可以发现主线程执行pthread_exit函数后子线程还可以执行
#includestdio.h
#includestdlib.h
#includestring.h
#includesys/types.h
#includeunistd.h
#include pthread.h
void *mythread(void *arg)
{sleep(1);//保证主线程先执行printf(child thread,pid[%d],id[%ld]\n,getpid(),pthread_self());
}
int main()
{//int pthread_create(pthread_t *thread, const pthread_attr_t *attr,// void *(*start_routine) (void *), void *arg);pthread_t thread;int retpthread_create(thread,NULL,mythread,NULL);if(ret!0){printf(pthread_create error:[%s]\n,strerror(ret));return -1;}printf(father thread,pid[%d],id[%ld]\n,getpid(),pthread_self());pthread_exit(NULL);
}pthread_join函数
函数作用阻塞等待线程退出获取线程退出状态。其作用跟进程的waitpid函数相似
函数原型int pthread_join(pthread_t thread, void **retval);
函数返回值
成功返回0失败返回错误号
函数参数
thread:线程id
retval:存储线程结束状态整个指针和pthread_exit的参数是同一块内存地址
#includestdio.h
#includestdlib.h
#includestring.h
#includesys/types.h
#includeunistd.h
#include pthread.h
void *mythread(void *arg)
{int *p(int *)malloc(sizeof(int));或者用全局变量*p9;printf(child thread,id[%ld],add[%p]\n,pthread_self(),p);pthread_exit(p);
}
int main()
{//int pthread_create(pthread_t *thread, const pthread_attr_t *attr,// void *(*start_routine) (void *), void *arg);pthread_t thread;int retpthread_create(thread,NULL,mythread,NULL);if(ret!0){printf(pthread_create error:[%s]\n,strerror(ret));return -1;}// int pthread_join(pthread_t thread, void **retval);void *ptmalloc(sizeof(void));pthread_join(thread,pt);int n*(int *)pt;printf(child exit status:[%d],add[%p]\n,n,pt);
} 可以发现p和pt的地址是一样的 pt存储了线程结束状态