LINUX学习笔记17——多线程

 

1.         线程理论基础:

a)         比进程更节俭:线程所有代码数据都是共享的

b)         方便:因为数据共享,所以通信方便

c)         遵循POSIX线程接口,称为pthread,需要#include

2.         创建线程:int pthread_create(pthread_t *tidp, const pthread_attr *attr, void *(start_rtn)(void), void *arg)

a)         Tidp:用来获取创建线程的ID

b)         Attr:线程属性,一般为NULL

c)         Start_rtn:线程要执行的函数,函数执行完了,线程也就完了!

d)         Arg:start_rtn的参数,注意是空指针变量,使用时需要进行类型强制转换。

e)         编译:Pthread的库不是LINUX系统的库,编译时需要加上,

1.         #gcc filename –lpthread:l指定自己加的库

f)          注意:线程优先共享全局变量,共享数据段!而局部变量处于堆栈处,不共享。

3.         线程终止:

a)         程序从启动历程中返回。

b)         线程可以被另一个进程终止。创建线程的进程结束了,线程也就结束了。

c)         线程自己调用pthread_exit函数:void pthread_exit(void *rval_ptr)

1.         #include

2.         rval_ptr:获取线程退出返回值的指针

4.         线程等待:int pthread_join(pthread_t tid, void **rval_ptr)

a)         作用:等待某个线程结束后再进行主程序。

b)         #include

c)         Tid:线程ID号

d)         Rval_ptr:线程返回值的指针,就看你是否需要返回值,不需要填NULL

e)         注意:创建线程后处于就绪态,需要主进程有线程等待的时间,线程才能有时间运行。

5.         获取线程ID: pthread_t  pthread_self(void)

a)         #include

6.         退出保护:

a)         当程序非正常退出时,清除栈空间。

b)         void pthread_cleanup_push(void (*rth)(void *), void *arg)

1.         #include

2.         用push函数和pop把程序段括起来

3.         将清除函数压入清除栈,当被括程序没运行到POP就退出时,调用清理函数,不包括return。如果有多条PUSH时,先进后出

4.         Rtn:清除函数

5.         Arg:清除函数的参数

c)         void pthread_cleanup_pop(int execute)

1.         #include

2.         将清除函数弹出清除栈

3.         Execute:决定是否在弹出清理函数的同时执行该函数,非0:执行;0:不执行

d)         清除函数:就是自己定义的内容,最主要的是得有return语句

你可能感兴趣的:(LINUX系统,linux,多线程,join,c)