Linux线程终止

网友投稿 238 2022-09-30

Linux线程终止

进程中的任一线程调用了exit,_Exit或者_exit,那么整个进程都会终止。      单个线程在不终止整个进程的情况下停止它的控制流,有三种方式:(1)线程只是从启动例程中返回,返回值是线程的退出码。(2)线程可以被同一进程中的其他线程取消。(3)线程调用pthread_exit。1、单个线程调用exit,_Exit或者_exitvoid* task1(void* arg){ while (1) {sleep(1);printf("thread1 running...\n");} return NULL;}void* task2(void *arg){  while (1) {sleep(1);printf("thread2 running...\n");}  return NULL;}void* task3(void *arg){ int i = 0; while (i++ < 5) {sleep(1);printf("thread3 running...\n");} exit(1); //_Exit(1); //_exit(1); return NULL;}int main(int argc, char *argv[]){ pthread_t thrd1, thrd2, thrd3; pthread_create(&thrd1, NULL, (void*)task1, NULL); pthread_create(&thrd2, NULL, (void*)task2, NULL); pthread_create(&thrd3, NULL, (void*)task3, NULL); pthread_join(thrd1, NULL); pthread_join(thrd2, NULL); pthread_join(thrd3, NULL); printf("Main thread exit...\n"); return 0;}程序输出:[root@robot ~]# vim thread_exit.c[root@robot ~]# gcc thread_exit.c -lpthread -o thread_exit[root@robot ~]# ./thread_exitthread2 running...thread3 running...thread1 running...thread2 running...thread3 running...thread1 running...thread2 running...thread3 running...thread1 running...thread2 running...thread3 running...thread1 running...thread2 running...thread3 running...[root@robot ~]#这里可以看到调用exit、_Exit、_exit会使整个进程退出。2、单个线程调用pthread_exitvoid pthread_exit(void* rval_ptr);rval_ptr是一个无类型指针,可以通过调用pthread_join函数访问到这个指针。void* task1(void* arg){ int i = 0; while (i++ < 5) { sleep(1); printf("thread1 running...\n"); } pthread_exit((void*)23); return NULL;}int main(int argc, char *argv[]){ pthread_t thrd1, thrd2, thrd3; void* tret; pthread_create(&thrd1, NULL, (void*)task1, NULL); pthread_join(thrd1, &tret); printf("thread1 return code:%d\n", (int)tret); printf("Main thread exit...\n"); return 0;}程序输出:[root@robot ~]# gcc thread_exit.c -lpthread -o thread_exit[root@robot ~]# ./thread_exitthread1 running...thread1 running...thread1 running...thread1 running...thread1 running...thread1 return code:23Main thread exit...[root@robot ~]#

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Azure新知识科普 - 分享个能即时获取最新Azure Update的python脚本
下一篇:使用JPA传递参数的方法
相关文章

 发表评论

暂时没有评论,来抢沙发吧~