Unix环境变量--线程基础

 

int pthread_equal(pthread_t tid1, pthread_t tid2);

头文件:#include <pthread.h>

返回值:若相等则返回非0值,否则返回0值

作用:判断两个线程ID是否相等

pthread_t pthread_self(void);

头文件:#include <pthread.h>

返回值:调用线程自身的线程ID

int pthread_create(pthread_t *tidp, const pthread_attr_t * attr, void *(*start_rtn)(void *), void *restrict arg);

头文件: #include <pthread.h>

参数:tidp:存放的是新线程的线程ID,

attr:用于定制各种不同的线程属性,为NULL,创建一个具有默认属性的线程。

start_rtn:新创建的线程从start_rtn函数的地址开始运行,该函数只有一个无类型指针参数arg


线程退出的三种方式:

(1)int pthread_cancel(pthread_t thread); 

作用:请求同进程的指定的线程thread退出,但实际是否生效不确定

(2)int pthread_exit(void* state); 

作用:退出当前线程,并返回状态

(3)线程函数直接return

int pthread_join(pthread_t thread, void **retval);

参数:pthread_t thread: 等待的线程的线程id

void **retval   : 等待的线程的返回的错误码,包括pthread_exit()函数或直接return的状态

注意:此函数只对那些线程属性不是分离的才有作用,否则直接返回错误EINVAL.

int pthread_detach(pthread_t tid);

作用:分离指定线程


线程的高级应用:

void pthread_cleanup_push(void (*rtn)(void *), void *arg);

参数:rtn:一个函数指针,指向一个自定义的清理函数

arg:传给清理函数的参数

作用:该函数用来将一个函数压入(或者注册)到一个清理函数栈的顶端。

头文件:#include <pthread.h>

  void pthread_clean_pop(int execute);

  头文件:#include <pthread.h>

参数:execute:为零时,移除pthread_cleanup_push()压入(或者叫注册)的清理函数,当为非零时,表示执行pthread_cleanup_push()压入(或者叫注册)的清理函数。

注意:(1)当一个线程被取消时,这些清理函数会以与push注册时相反的顺序被执行,且执行后被从栈中移除

(2)通过调用函数pthread_exit()终止线程时,这些清理函数被调用,但是如果用return语句来终止线程,则不会调用这些清理函数

(3)当调用pthread_cleanup_pop()函数且其参数为非零时,就调用栈顶的清理函数执行,且执行完后,就将该清理函数从栈中移除

(4)对函数pthread_cleanup_push()和函数pthread_clean_up()的调用必须成对出现,否则编译出错

猜你喜欢

转载自blog.csdn.net/Chiang2018/article/details/105418654