[9]Linux多线程
2017-02-03 09:57
375 查看
相关函数API支持:
phread支持库:
Linux系统下的多线程遵循POSIX线程接口,称为pthread。编写Linux下的多线程程序,需要使用头文件pthread.h,连接时需要使用库libpthread.a。gcc -lpthread helloworld.c -o helloworld
创建线程:
#include <pthread.h> int pthread_create(pthread_t * tidp,const pthread_attr_t *attr,void *(*start_rtn)(void),void *arg);
tidp:线程id(输出参数);
attr:线程属性(通常为空);
start_rtn:线程要执行的函数;
arg:start_rtn的参数;
返回值:成功,返回0;出错,返回-1。
线程终止:
如果进程中任何一个线程中调用exit或_exit,那么整个进程都会终止。线程的正常退出方式有:(1) 线程从启动例程中返回;
(2) 线程可以被进程中的另一个线程程终止;
(3) 线程自己调用pthread_exit函数。
pthread_exit
#include <pthread.h> void pthread_exit(void * rval_ptr);
使用函数pthread_exit退出线程,这是线程的主动行为;由于一个进程中的多个线程是共享数据段的,因此通常在线程退出之后,退出线程所占用的资源并不会随着线程的终止而得到释放。pthread_exit()调用线程的返回值,可由其他函数如pthread_join来检索获取。
rval_ptr:线程返回值指针。
pthread_join
#include <pthread.h> int pthread_join(pthread_t tid,void **rval_ptr);
阻塞调用线程,直到指定的线程终止。
tid :等待退出的线程id;
rval_ptr:线程退出的返回值的指针;
返回值:成功返回0,否则返回非0。
线程标识
#include <pthread.h> pthread_t pthread_self(void)
获取调用线程的线程标识。
线程终止与资源释放
线程终止
线程终止有两种情况:正常终止和非正常终止。线程主动调用pthread_exit或者从线程函数中return都将使线程正常退出,这是可预见的退出方式;非正常终止是线程在其他线程的干预下,或者由于自身运行出错(比如访问非法地址)而退出,这种退出方式是不可预见的。
不论是可预见的线程终止还是异常终止,都会存在资源释放的问题,如何保证线程终止时能顺利的释放掉自己所占用的资源,是一个必须考虑解决的问题。
资源释放
在POSIX线程API中提供了一个pthread_cleanup_push()/pthread_cleanup_pop()函数对用于自动释放资源 –从pthread_cleanup_push()的调用点到pthread_cleanup_pop()之间的程序段中的终止动作(包括调用 pthread_exit()和取消点终止)都将执行pthread_cleanup_push()所指定的清理函数。#include <pthread.h> void pthread_cleanup_push(void (*rtn)(void *),void *arg);
将清除函数压入清除栈。
- rtn:清除函数(函数指针)
- arg:清除函数的参数
#include <pthread.h> void pthread_cleanup_pop(int execute);
将清除函数弹出清除栈。
- execute执行到pthread_cleanup_pop()时是否在弹出清理函数的同时执行该函数,非0:执行; 0:不执行。
线程同步
待续相关文章推荐
- Linux socket 初步
- Linux Kernel 4.0 RC5 发布!
- Python3写爬虫(四)多线程实现数据爬取
- linux lsof详解
- linux 文件权限
- Linux 执行数学运算
- 10 篇对初学者和专家都有用的 Linux 命令教程
- Linux 与 Windows 对UNICODE 的处理方式
- Ubuntu12.04下QQ完美走起啊!走起啊!有木有啊!
- 解決Linux下Android开发真机调试设备不被识别问题
- 运维入门
- 运维提升
- Linux 自检和 SystemTap
- Ubuntu Linux使用体验
- c语言实现hashmap(转载)
- Linux 信号signal处理机制