您的位置:首页 > 运维架构 > Linux

Linux线程基础函数

2016-03-28 22:34 513 查看
1. 线程标识:

(1) 比较两个线程ID;

#include <pthread.h>

int pthread_equal(pthread_t tid1, pthread_t tid2);

ret-若相等则返回非0值,否则返回0值


(2) 获取线程自身ID;

#include <pthread.h>

pthread_t pthread_self(void);

ret-调用线程的线程ID


2. 线程的创建:

#include <pthread.h>

int pthread_create(pthread_t *restrict tidp, //返回线程的ID

           const pthread_attr_t *restrict attr, //线程属性,默认为NULL

void *(*start_rtn)(void), //线程函数入口地址

void *restrict arg); //参数

ret-成功返回0 失败返回错误编号


3. 线程的终止:

(1) 线程只是从启动例程中返回,返回值是线程的退出码;

(2) 线程可以被同一例程中的其他线程取消;

(3) 线程调用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);

ret-成功返回0 否则返回错误编号


调用线程一直阻塞,知道指定的线程调用pthread_exit,从启动例程中返回或者被取消;如果线程只是从他的启动例程中返回,rval—_ptr将包含返回码;如果线程被取消,由rval_ptr指定的内存单元就设置为PTHREAD_CANCELED.

如果线程已经处于分离状态,pthread_t就会调用失败,返回EINVAL。

如果对线程的返回值不感兴趣,可以吧rval_prt设置为NULL。这种情况下,调用pthread_join将等待线程终止,但不获取线程的终止状态。

4. 线程取消:

#include <pthread.h>

int pthread_cancel(pthread_t tid);

ret-成功返回0 失败返回错误码


函数使得由tid标识的线程行为表现为如果调用了参数是PTHREAD_CANCELD的pthread_exit函数,但是,线程可以选择忽略取消方式或者是控制取消方式。函数并不等待线程终止,它仅仅是提出请求;

5. 线程清理处理函数:

#include <pthread.h>

void pthread_cleanup_push(void(*rtn)(void*), void *arg);
void pthread_cleanup_pop(int execute); //调用删除上次push的清理程序


当线程执行以下动作时调用清理函数,调用者参数为arg,清理函数rtn的调用顺序是由pthread_cleanup_pus来安排的。

a. 调用pthread_exit;

b. 想用取消请求;

c. 用非零的execute参数调用pthread_cleanup_pop;

如果execute=0则函数不被调用;

注意正常从线程返回的时候,不会调用该清理函数;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: