外贸网站 站长工具,网站seo优化免,wordpress hero theme,wordpress程序安装1、线程结束的方式
#xff08;1#xff09;线程函数中调用pthread_exit函数#xff0c;不会导致对象析构#xff0c;可以使用#xff08;2#xff09;线程所属的进程结束#xff0c;进程调用exit#xff0c;线程C对象不会销毁#xff0c;不安全#xff0c;属于被动…1、线程结束的方式
1线程函数中调用pthread_exit函数不会导致对象析构可以使用2线程所属的进程结束进程调用exit线程C对象不会销毁不安全属于被动结束3线程函数执行返回return好的退出方式4线程被同一进程或其他线程通知结束属于被动结束
2、线程主动结束
线程主动结束使用return或者pthread_exit函数原型如下
void pthread_exit(void *retval);
retval是线程返回给主线程的值线程函数返类型是void *。在main线程中调用pthread_exit(NULL)将结束main线程但是进程不立即退出。
示例
#include pthread.h
#include stdio.h
#include string.h
#include unistd.hvoid thread_fun(void *arg)
{static int count 1;//必须静态传出的地址不改变pthread_exit((void*)count);
}
int main(int argc,char * argv[])
{int *pretv;int pid;if(0 ! pthread_creat(pid,NULL,(void *(*)(void *))thread_fun,NULL)){printf(pthread creat error\n);return -1;}pthread_join(pid,(void**)pretv);printf(thread fun retval:%d\n,*pretv);return 0;
}
3、线程被动结束
线程被动结束的两种方法
同一进程的其他线程中通过函数pthread_kill发送信号给要结束的进程目标进程收到后再退出同一进程的其他线程中通过函数pthread_cancel取消目标的执行
pthread_kill的函数原型
void pthread_kill(pthread_t pid, int signal);
pid接收信号线程的线程IDsignal就是信号大于0的值如果等于0就是探测线程是否存在执行成功返回0否则返回错误码ESRCH线程不存在EINVAL信号不合法。
向指定线程发送信号如果线程代码不处理则调用信号的默认处理方法。线程信号例如Linux 进程通信 -- 信号
https://blog.csdn.net/u010058695/article/details/102787168
pthread_cancel的函数原型
void pthread_cancel(pthread_t pid);
pid要被取消线程的ID向指定线程发送取消执行的请求请求终止但不一定就终止系统不会马上取消线程只有在被取消线程下次调用一些C库函数如printf或者pthread_testcancel(让内核去检测是否需要取消当前线程)时才会真正结束在线程执行过程中检测是否有未响应取消信号的地方叫做取消点。
示例
#include pthread.h
#include stdio.h
#include string.h
#include unistd.hvoid thread_fun(void *arg)
{int count 0;while(1){i;pthread_testcancel();}return;
}
int main(int argc,char * argv[])
{int *pretv;int pid;if(0 ! pthread_creat(pid,NULL,(void *(*)(void *))thread_fun,NULL)){printf(pthread creat error\n);return -1;}pthread_cancel(pid);pthread_join(pid,(void**)pretv);return 0;
}