参考:https://blog.csdn.net/u010383937/article/details/78215287
https://www.cnblogs.com/lijunamneg/archive/2013/01/25/2877211.html
phtread_join():监控等待线程结束,阻塞接口。类似进程的wait()
pthread_cancel():需要设置被取消线程取消使能、取消类型(延迟、异步)。然后在自己线程里取消该线程
1- phtread_join():监控等待线程结束,阻塞接口。类似进程的wait()
pthread_exit():线程自行退出,类似进程的exit()
示例:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<pthread.h>
void * thread_strat(void *message)
{
printf("%s[%d] %s thread=%lu \n",__func__,__LINE__,(const char *)message,pthread_self());
sleep(1);
printf("%s[%d] thread=%lu here is thread\n",__func__,__LINE__,pthread_self());
/*线程自行退出:return、pthread_exit*/
pthread_exit(NULL);
//return message;
}
int main(void)
{
pthread_t thread;
int ret;
const char *message = "creat thread succ";
/*只是创建线程,并不执行*/
ret = pthread_create(&thread,NULL,thread_strat,(void *)message);
if(!ret)
{
perror("pthread_creat");
}
printf("%s[%d] thread=%lu \n",__func__,__LINE__,pthread_self());
/*等待线程thread结束,期间自己阻塞挂起。当thread结束后才返回*/
pthread_join(thread,NULL);
printf("%s[%d] i'm comming!\n",__func__,__LINE__);
return 0;
}
2- 线程取消和清理
pthread_cancel():需要设置被取消线程取消使能、取消类型(延迟、异步)。然后在自己线程里取消该线程
pthread_cleanup_push/pop():释放线性资源
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<pthread.h>
void * thread_strat(void *message)
{
printf("%s[%d] %s thread=%lu \n",__func__,__LINE__,(const char *)message,pthread_self());
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);//PTHREAD_CANCEL_DEFERRED
while(1)
{
printf("%s[%d] thread=%lu here is thread\n",__func__,__LINE__,pthread_self());
}
/*线程自行退出:return、pthread_exit*/
pthread_exit(NULL);
//return message;
}
int main(void)
{
pthread_t thread;
int ret;
const char *message = "creat thread succ";
/*只是创建线程,并不执行*/
ret = pthread_create(&thread,NULL,thread_strat,(void *)message);
if(!ret)
{
perror("pthread_creat");
}
printf("%s[%d] thread=%lu \n",__func__,__LINE__,pthread_self());
/*取消线程*/
pthread_cancel(thread);
printf("%s[%d] i'm comming!\n",__func__,__LINE__);
return 0;
}