pthread_exit-----在linux主线程中的用途
来源:互联网 发布:淘宝平板版下载 编辑:程序博客网 时间:2024/06/07 17:28
大家都知道在一个线程中调用pthread_exit表示退出一个线程,并且pthread_exit的参数作为返回值提供给pthread_join函数获取。
那么如果在main函数创建了若干个线程后,在main函数最后调用pthread_exit会怎么样呢?已经创建的线程会不会随着main线程的退出而退出呢?
如果在main函数中调用的是exit,那么答案是所有线程随着main线程退出而退出。
但是对于pthread_exit而言,又是另外一个故事了。
在main函数中调用pthread_exit, 只有main线程自己退出,已经创建的线程并不会随之一起退出。
#include <stdio.h>#include <stdlib.h>#include <pthread.h>#include <string.h>#include <errno.h>#include <sys/types.h>#include <unistd.h>pthread_t ntid;void printtids(const char *s) { pid_t pid; pthread_t tid; pid = getpid(); tid = pthread_self(); printf("%s pid %u tid %u (0x%x)\n", s, (unsigned int)pid, (unsigned int)tid, (unsigned int)tid);}void *thread_func(void *arg){ sleep(1); /*故意在子线程中sleep 1,保证子线程在main线程以后退出*/ printtids("new thread: "); return NULL; }int main(int argc, char *argv[]){ int rc; rc = pthread_create(&ntid, NULL, thread_func, NULL); if (rc != 0) { printf("pthread_create error: %s\n", strerror(errno)); } printtids("main thread: "); pthread_exit(NULL); /*main线程退出,后面的话不会打印了*/ printf("main process is exited...\n"); return 0;}
编译运行:
发现进程ID是一样的,线程ID不一致,并且在”main thread…”, 输出以后停顿了一下(sleep 1)后输出”new thread…”.
而且没有输出“main process is exited…”
说明pthread_exit 只退出了main线程,其它线程并没有随之退出
gwwu@hz-dev2.aerohive.com:~/test/thread>gcc -g thread1.c -o thread1 -lpthread -Wallgwwu@hz-dev2.aerohive.com:~/test/thread>./thread1 main thread: pid 19066 tid 291600128 (0x11617700)new thread: pid 19066 tid 291591936 (0x11615700)gwwu@hz-dev2.aerohive.com:~/test/thread>
阅读全文
0 0
- pthread_exit-----在linux主线程中的用途
- linux下pthread_exit在主线程中的用途
- 在主线程上
- C# 在工作线程中调用主线程中的方法
- Handler.post(Runable),Runable是运行在主线程中的。
- hadoop在移动中的用途
- const在项目中的用途
- Python在测试中的用途
- pthread_exit()
- pthread_exit
- pthread_exit
- pthread_exit()
- pthread_exit()
- pthread_exit()
- pthread_exit
- pthread_exit()
- pthread_exit()
- Linux线程pthread_exit 和 pthread_join
- RandomAccessFile的编码转换问题
- javascript逻辑运算符“||”和“&&”
- dfsput操作报“There are 0 datanode(s) running and no node(s) are excluded in this operation”
- URG_PSH区别
- java学习笔记1——面向对象和JVM基础
- pthread_exit-----在linux主线程中的用途
- 【翻译】Faster-R-CNN: Towards Real-Time Object Detection with Region Proposal Networks
- 端午个人赛-A return of Nim (Nim+威左夫,拓:巴什)
- MediaStore.Audio.Media属性(本地媒体库)
- Android常用开源项目(二十八)
- nginx配合modsecurity实现WAF功能
- 实现View的简单滑动2
- HDU 4794 斐波那契数列循环节
- 用Dialog实现底部弹窗