linux c之使用pthread_create创建线程pthread_join等待线程和pthread_exit终止线程总结
2017-03-06 21:33
417 查看
1、介绍API
1、pthread_create函数
函数简介pthread_create是UNIX环境创建线程函数
头文件
#include<pthread.h>
函数声明
int pthread_create(pthread_t *restrict tidp,const pthread_attr_t *restrict_attr,void*(*start_rtn)(void*),void *restrict arg);
返回值
若成功则返回0,否则返回出错编号
参数
第一个参数为指向线程标识符的指针,第二个参数用来设置线程属性,第三个参数是线程运行函数的起始地址, 最后一个参数是运行函数的参数。
另外在编译时注意加上-lpthread参数,以调用静态链接库。因为pthread并非Linux系统的默认库
2、pthread_join函数
函数简介函数pthread_join用来等待一个线程的结束。
函数原型为:
extern int pthread_join __P (pthread_t __th, void **__thread_return);
参数:
第一个参数为被等待的线程标识符,第二个参数为一个用户定义的指针,它可以用来存储被等待线程的返回值。这个函数是一个线程阻塞的函数,调用它的函数将一直等待到被等待的线程结束为止,当函数返回时,被等待线程的资源被收回。如果执行成功,将返回0,如果失败则返回一个错误号。
3、pthread_exit函数
函数原型void pthread_exit(void* retval);
函数简介
线程通过调用pthread_exit函数终止执行,就如同进程在结束时调用exit函数一样。这个函数的作用是,终止调用它的线程并返回一个指向某个对象的指针。
2、爆图爆代码
实现创建2个线程打印数据3、结果展示
我们知道pthread_t得大小是8
然后pthread_exit是退出线程,看上面红色的标记就知道,线程id只有一个了,然后pthread_join是阻塞的,等待线程结束,如果不用这个函数,直接ruturn的话,可能看不到打印,读者可以自己测试下,pthread_create是创建线程的,注意是传函数地址,也就是函数名,不是&函数名。
相关文章推荐
- Linux下多线程编程__线程的创建pthread_create与退出pthread_exit,等待当前线程退出pthread_join,获取线程ID pthread_self
- pthread_create创建线程后必须使用join或detach释放线程资源[内存泄漏]
- 线程相关函数(1)-pthread_create(), pthread_join(), pthread_exit(), pthread_cancel() 创建取消线程
- pthread_create创建线程后必须使用join或detach释放线程资源[内存泄漏]
- 线程原语:pthread_create(),pthread_self(),pthread_exit(),pthread_join(),pthread_cancel(),pthread_detach(
- 线程终止thread_exit,pthread_cancel,pthread_join
- c与c++在使用pthread_create创建线程时的区别
- 对线程创建函数pthread_create的总结
- 线程正常终止pthread_exit,pthread_join,pthread_kill,pthread_cancel,sigwait,sigaddset
- 线程正常终止pthread_exit,pthread_join,pthread_kill,pthread_cancel,sigwait,sigaddset
- [置顶] 【Linux】线程总结:初识、创建、等待、终止、分离
- linux 线程等待与退出 pthread_join pthread_exit 函数
- 使用pthread_create创建大量线程时,创建线程失败,Resource temporarily unavailable的解决办法
- 2线程原语:pthread_create(),pthread_self(),pthread_exit(),pthread_join(),pthread_cancel(),pthread_detach(
- Linux学习-线程的创建和终止-(出现错误-undefined reference to 'pthread_create')
- c++ Pthread创建线程后必须使用join或detach释放线程资源
- Pthread创建线程后必须使用join或detach释放线程资源
- 线程原语:pthread_create(),pthread_self(),pthread_exit(),pthread_join(),pthread_cancel(),pthread_detach(
- Pthread创建线程后必须使用join或detach释放线程资源
- 使用pthread_create()创建线程