unix环境高级编程-线程的标识,创建,终止

1. 线程标识

每个线程有个线程ID
线程ID用 pthread_t 数据类型表示,是一个非负整数

  1. 线程比较函数
#include <pthread.h>
int pthread_equal(pthread_t tid1,pthread_t tid2); // 返回值:若相等返回非0;否则返回0                   
  1. 线程可通过调用 pthread_self 函数获得自身线程ID
#include <pthread.h>
pthread_t pthread_self(void); //  返回值:调用线程的线程ID                  

2. 线程创建

在POSIX线程下,程序运行时,也是以单进程中的单个线程启动。

  1. 新增线程函数 pthread_create
#include <pthread.h>
int pthread_create(pthread_t *restrict tidp,const pthread_attr_t attr,void *(*start_rtn)(void *),void *restrict arg);
        //成功返回0,错误返回错误编号

pthread_create成功返回时,新的线程ID设置成tidp指向的内存.attr用于定制线程的属性,默认属性设置为NULL。新线程从 start_run 函数开始运行,将arg空指针参数传递过去。
线程创建时并不能保证哪个线程会先运行,新创建的线程可以访问进程的地址空间,并且继承调用点成的浮点环境和信号屏蔽字,但是该线程的未决信号集被清除。
注意:
pthread函数在调用失败后通常返回错误码,它们并不像其他POSIX函数一样设置errno,所以通常使用strerror函数将
错误代码翻译成描述信息,而不能直接使用perror函数取errno进行翻译。
gcc 编译多线程程序时 -pthread 链接线程库

3. 线程的终止

  1. 进程中任意线程调用 exit ,_exit,_Exit ,整个进程终止
  2. 单个进程3中方式退出
  3. 线程从启动例程返回
  4. 线程被同进程其他线程取消
  5. 线程调用pthread_exit
#include <pthread.h>
void pthread_exit(void *rval_ptr);

rval_ptr 时无参数指针,其他线程可通过pthread_join访问

#include<pthread.h>
int pthread_join(pthread_t thread,void **rval_ptr);//成功返回0,否则返回错误编号

调用线程一直阻塞,,直到指定线程调用pthread_exit,从启动例程返回,或被取消
如果线程只是从它的启动例程返回,rval_ptr将包含返回码。如果线程被取消,由rval_ptr指定的内容单元就置为PTHREAD_CANCELED。
如果对线程的返回值不感兴趣,可以把rval_ptr置为NULL。

  1. 线程调用pthread_cancel取消同一进程中其他线程
#include <pthread.h>
int pthread_cancel(pthread_t tid);  //成功返回0,错误返回错误编号

非阻塞,仅仅提出取消请求
4. 线程可以安排线程清理处理程序,执行顺序与注册相反

#include <pthread.h>
void pthread_clenup_push(void (*rtn)(void *),void *arg);
void pthread_cleanup_pop(int execute);
  1. 线程被分离后,线程终止时,资源被立即回收,否则只能等待pthread_join后再回收
#include <pthread.h>
int pthread_detach(pthread_t tid);
posted @ 2016-10-24 14:02  时过境迁。  阅读(141)  评论(0)    收藏  举报