一篇带你完全掌握线程的博客
2018-09-21 09:11
597 查看
前言:最近一直在疯狂学习,之前也不太了解线程,现在基本都掌握了。如果你之前也不知道线程,也不知道进程和线程的区别等等,这一篇博客带你完全掌握,不掌握不要钱,哈哈哈!
View Code
编译:gcc pthread_cre.c -lpthread,记得链接线程库 -lpthread
pthread_exit函数
功能:将单个线程退出 相当于exit
原型:void pthread_exit(void *retval);
参数:retval表示线程退出状态,通常传NULL
pthread_join函数
功能:阻塞等待线程退出,获取线程退出状态 其作用,对应进程中 wait()、waitpid() 函数。
原型:int pthread_join(pthread_t thread, void **retval);
参数:thread:线程ID (【注意】:不是指针);retval:存储线程结束状态。
pthread_detach函数
功能:实现线程分离 线程独有的,没有进程的相关函数与之对应
原型:int pthread_detach(pthread_t thread);
线程分离状态:指定该状态,线程主动与主控线程断开关系。线程结束后,其退出状态不由其他线程获取,而直接自己自动释放。网络、多线程服务器常用。
重点:分离状态的线程就不需要回收了!!!重要的事情说三遍,三遍,三遍!!!
pthread_cancel函数
功能:杀死(取消)线程 其作用,对应进程中 kill() 函数。
原型:int pthread_cancel(pthread_t thread);
【注意】:线程的取消并不是实时的,而有一定的延时。需要等待线程到达某个取消点(检查点)。
进程 线程
fork pthread_create
exit pthread_exit
wait pthread_join
kill pthread_cancel
getpid pthread_self
总结:欢迎评论,交流与学习。
一、线程概念
介绍概念之前,先画个图吧,依旧是全博客园最丑图,不接受反驳!#include<stdio.h> #include<unistd.h> #include<pthread.h> void *tfn(void *arg) { printf("child thread%lu\n",pthread_self()); return NULL; } int main() { pthread_t tid; pthread_create(&tid,NULL,tfn,NULL); sleep(1); printf("main thread:%lu\n",pthread_self()); return 0; }
View Code
编译:gcc pthread_cre.c -lpthread,记得链接线程库 -lpthread
pthread_exit函数
功能:将单个线程退出 相当于exit
原型:void pthread_exit(void *retval);
参数:retval表示线程退出状态,通常传NULL
pthread_join函数
功能:阻塞等待线程退出,获取线程退出状态 其作用,对应进程中 wait()、waitpid() 函数。
原型:int pthread_join(pthread_t thread, void **retval);
参数:thread:线程ID (【注意】:不是指针);retval:存储线程结束状态。
pthread_detach函数
功能:实现线程分离 线程独有的,没有进程的相关函数与之对应
原型:int pthread_detach(pthread_t thread);
线程分离状态:指定该状态,线程主动与主控线程断开关系。线程结束后,其退出状态不由其他线程获取,而直接自己自动释放。网络、多线程服务器常用。
重点:分离状态的线程就不需要回收了!!!重要的事情说三遍,三遍,三遍!!!
pthread_cancel函数
功能:杀死(取消)线程 其作用,对应进程中 kill() 函数。
原型:int pthread_cancel(pthread_t thread);
【注意】:线程的取消并不是实时的,而有一定的延时。需要等待线程到达某个取消点(检查点)。
六、控制原语对比
就是就是将进程相关函数与线程函数,进行对比来记忆:进程 线程
fork pthread_create
exit pthread_exit
wait pthread_join
kill pthread_cancel
getpid pthread_self
总结:欢迎评论,交流与学习。
相关文章推荐
- 3.2.1 一篇文章完全掌握 RecycleView 的六大用法
- 一篇博客说完HTML
- 华为boss力荐公司高层看的一篇文章,真的很经典!【转载于m13666368773的一篇博客】
- 有关数据死锁问题的一篇好文章,一个好博客
- mush上线,一篇关于技术的博客,欢迎关注!
- 关于Java中进程与线程的初步认识与掌握
- 使用GCD处理后台线程和UI线程的交互(转自唐巧的技术博客)
- 怎么样写好一篇技术博客
- c#编程指南(十五) 平台调用P-INVOKE完全掌握(完结篇),自定义Mashaler
- 搞笑--一篇有趣的文章编译自一篇西班牙博客。有一位美丽的公主,被关押在一个城堡中最高的塔上,一条凶恶的巨龙看守着她,需要有一位勇士营救她…
- こっそり==そっくり==たっぷり==5分钟--完全掌握6个日语N2常考副词。---路得老师学日语
- 本站的最后一篇博客
- 转载一篇坚持写博客的好处,以勉励自己
- BOOST 线程完全攻略 - 结束语
- 自学通过CCNA考试完全指南—51CTO博客专题
- 一步一步掌握java的线程机制(一)----创建线程
- 掌握电商后台设计,这一篇足矣 | 万字长文
- win10下deepwalk配置和运行(对网上有一篇博客教程的改进)
- BOOST 线程完全攻略 - 扩展 - 可被关闭的线程类
- 小松博客文章上一篇下一篇样式修改