自学嵌入式第二十九天:Linux系统编程-线程
一、线程
1.线程是轻量级进程,一般是一个进程中的多个任务;
2.比多进程节省资源,可以共享变量;
3.进程是系统中最小的资源分配单位,线程是系统中最小的执行单位;
4.进程里会自动启动主线程(main_thread);
5.特征:
(1)只有独立栈区,其他全部共享,共享资源;
(2)效率高30%;
(3)三方库:pthread clone posix
编写时添加头文件,pthread.h
编译时,-lpthread library
库文件:libpthread.so
6.缺点
(1)比进程稳定性要差;
(2)gdb相对麻烦;
二、进程与线程
1.共同点:并发;
2.不同点
(1)创建的开销,proc 3G,thread 8M;
(2)proc数据不共享,thread除了栈区数据共享;
(3)稳定性:proc稳定,thread不稳定;
(4)proc(大任务),thread(大任务中需要并发的小任务);
(5)线程属于某个进程;
三、线程的编程
1.创建线程
int pthread_create(pthread_ *thread,const pthread_attr_t *attr,void *(*start routine)(void*),void *arg);
成功返回0;错误返回非零的错误号;
2.获得当前线程的线程号
pthread_t pthread_self();
%lu,线程号的类型是unsigned long;
返回值是线程号(内核层);
3.ps eLf 查看用户层的线程号
ps -eLo pid,ppid,lwp,stat,comm指定显示的内容
4.退出当前线程
void pthread_exit(void* retval);
如果在线程里调用exit则会结束所有线程;
5.结束一个线程
int pthread_cancle(pthread_t thread);
一般是其它线程关闭另一个线程;
6.回收
主线程不能先结束;
int pthread_join(pthread_t thread,void **retval);
thread是要回收的子线程tid;
retval是接收的子线程的返回值/状态,返回值如果是个int型,就需要提前指定一个int指针,把指针取地址放入;
阻塞等待;
7.设置分离属性
目的线程消亡自动回收空间;
int pthread_detach(pthread_t thread);
8.线程清理函数
void pthread_cleanup_push(void(*routine)(void*),void *arg);
注册一个清理函数routine;
void pthread_cleanup_pop(int execute);
execute为真时调用清理函数;
类似于do{}while();