pthread

来源:互联网 发布:有域名了怎么建立网站 编辑:程序博客网 时间:2024/06/11 04:27
POSIX线程(POSIX threads),简称Pthreads,是线程的POSIX标准。该标准定义了创建和操纵线程的一整套API。在类Unix操作系统(Unix、Linux、Mac OS X等)中,都使用Pthreads作为操作系统的线程。

1、pthread相关函数

#include <pthread.h>
//新建线程
int pthread_create(pthread_t *restrict tidp, constpthread_attr_t *restrict attr,void*(*start_rtn)(void*),void*restrict arg);
  
//线程终止
void pthread_exit(void *rval_ptr);//线程自身主动退出
int pthread_join(pthread_t tid, void **rval_ptr);//其他线程阻塞自身,等待tid退出
  
//线程清理
voidpthread_cleanup_push(void(*rtn)(void*),void *arg);
voidpthread_cleanup_pop(intexecute);
 
另:
 
操纵函数
pthread_create():创建一个线程
pthread_exit():终止当前线程
pthread_cancel():中断另外一个线程的运行
pthread_join():阻塞当前的线程,直到另外一个线程运行结束
pthread_attr_init():初始化线程的属性
pthread_attr_setdetachstate():设置脱离状态的属性(决定这个线程在终止时是否可以被结合)
pthread_attr_getdetachstate():获取脱离状态的属性
pthread_attr_destroy():删除线程的属性
pthread_kill():向线程发送一个信号
 

Pthread同步函数

用于 mutex 和条件变量
pthread_mutex_init() 初始化互斥锁
pthread_mutex_destroy() 删除互斥锁
pthread_mutex_lock():占有互斥锁(阻塞操作)
pthread_mutex_trylock():试图占有互斥锁(不阻塞操作)。即,当互斥锁空闲时,将占有该锁;否则,立即返回。
pthread_mutex_unlock(): 释放互斥锁
pthread_cond_init():初始化条件变量
pthread_cond_destroy():销毁条件变量
pthread_cond_signal(): 唤醒第一个调用pthread_cond_wait()而进入睡眠的线程
pthread_cond_wait(): 等待条件变量的特殊条件发生
Thread-local storage(或者以Pthreads术语,称作线程特有数据):
pthread_key_create(): 分配用于标识进程中线程特定数据的键
pthread_setspecific(): 为指定线程特定数据键设置线程特定绑定
pthread_getspecific(): 获取调用线程的键绑定,并将该绑定存储在 value 指向的位置中
pthread_key_delete(): 销毁现有线程特定数据键
pthread_attr_getschedparam();获取线程优先级
pthread_attr_setschedparam();设置线程优先级
 

Pthread工具函数

pthread_equal(): 对两个线程的线程标识号进行比较
pthread_detach(): 分离线程
pthread_self(): 查询线程自身线程标识号

2、pthread_create()线程创建

函数简介

pthread_create是UNIX环境创建线程函数。创建线程(实际上就是确定调用该线程函数的入口点),在线程创建以后,就开始运行相关的线程函数。

头文件

#include<pthread.h>

函数声明

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

返回值

若成功则返回0,否则返回出错编号,返回-1。

参数

              第一个参数为指向线程标识符的指针。

              第二个参数用来设置线程属性。

              第三个参数是线程运行函数的起始地址。

              最后一个参数是运行函数的参数。

另外

在编译时注意加上-lpthread参数,以调用静态链接库。因为pthread并非Linux系统的默认库

 

    举例:

/*thread.c*/#include <stdio.h>#include <pthread.h>/*线程一*/void thread_1(void){    int i=0;    for(i=0;i<=6;i++)    {        printf("This is a pthread_1.\n");        if(i==2)            pthread_exit(0);        sleep(1);    }}/*线程二*/void thread_2(void){    int i;    for(i=0;i<3;i++)        printf("This is a pthread_2.\n");    pthread_exit(0);}int main(void){    pthread_t id_1,id_2;    int i,ret;/*创建线程一*/    ret=pthread_create(&id_1,NULL,(void  *) thread_1,NULL);    if(ret!=0)    {        printf("Create pthread error!\n");    return -1;    }/*创建线程二*/     ret=pthread_create(&id_2,NULL,(void  *) thread_2,NULL);    if(ret!=0)    {        printf("Create pthread error!\n");    return -1;    }/*等待线程结束*/    pthread_join(id_1,NULL);    pthread_join(id_2,NULL);    return 0;}

    以下是程序运行结果:

    备注:pthread库不是Linux系统默认的库,连接时需要使用静态库libpthread.a,所以线程函数在编译时,需要连接库函数,如上图    gcc pthread_create.c -o pthread_create -lpthread

 

3、pthread_join函数

函数简介

函数pthread_join用来等待一个线程的结束。

函数原型为:

extern int pthread_join __P (pthread_t __th, void **__thread_return);

参数:

第一个参数为被等待的线程标识符,第二个参数为一个用户定义的指针,它可以用来存储被等待线程的返回值。这个函数是一个线程阻塞的函数,调用它的函数将一直等待到被等待的线程结束为止,当函数返回时,被等待线程的资源被收回。如果执行成功,将返回0,如果失败则返回一个错误号。

例子:

#include<stdio.h>

#include<stdlib.h>

#include<pthread.h>

struct member

{

        int num;

        char *name;

};     

//结构体后的分号勿漏

void *create(void *arg)       

//有void* 型参数传入,不能直接void

{

        struct member *temp;

        temp=(struct member *)arg;      

//结构体变量之间不能直接赋值,但可以通过指针赋地址

        printf("member->num:%d\n",temp->num);

        printf("member->name:%s\n",temp->name);

        sleep(1);

        return (void *)8;     

//这个很有特色,返回一个指向void的数据类型的值,这个值作为后面的exit code

}

int main(int agrc,char* argv[])

{

        pthread_t tidp;

        struct member *b;

        void* a;

        b=(struct member *)malloc(sizeof(struct member));           

//先分配内存空间撒~

        b->num=1;

        b->name="mlq";              

//字符串赋值,其他好用简便的方法有:   char *p = NULL;   p = new char [256];

        if((pthread_create(&tidp,NULL,create,(void*)b))==-1)     /

//

void *

为“无类型指针”,void *  可以指向任何类型的数据

        {

                printf("create error!\n");

                return 1;

        }

 

4、pthread_detach()函数

pthread_detach(pthread_self())
linux线程执行和windows不同,pthread有两种状态joinable状态和unjoinable状态。创建一个线程默认的状态是joinable。


如果线程是joinable状态,当线程函数自己返回退出时或pthread_exit时都不会释放线程所占用堆栈和线程描述符(总计8K多)。只有当你调用了pthread_join之后这些资源才会被释放。但是调用pthread_join(pthread_id)后,如果该线程没有运行结束,调用者会被阻塞,在有些情况下我们并不希望如此。
若是unjoinable状态的线程,这些资源在线程函数退出时或pthread_exit时自动会被释放。


unjoinable属性可以在pthread_create时指定,或在线程创建后在线程中pthread_detach自己,如:pthread_detach(pthread_self()),将状态改为unjoinable状态,确保资源的释放。或者将线程置为joinable,然后适时调用pthread_join.

其实简单的说就是在线程函数头加上 pthread_detach(pthread_self())的话,线程状态改变,在函数尾部直接pthread_exit线程就会自动退出。省去了给线程擦屁股的麻烦

eg:

 pthread_t tid;
 int status = pthread_create(&tid, NULL, ThreadFunc, NULL);
 if(status != 0)
 {
  perror("pthread_create error");
 }
 pthread_detach(tid);

 

如在Web服务器中当主线程为每个新来的链接创建一个子线程进行处理的时候,主线程并不希望因为调用pthread_join而阻塞(因为还要继续处理之后到来的链接),这时可以在子线程中加入代码

pthread_detach(pthread_self())
或者父线程调用
pthread_detach(thread_id)(非阻塞,可立即返回)
这将该子线程的状态设置为detached,则该线程运行结束后会自动释放所有资源。

 

5、线程终止

a. 任一线程调用exit, _Exit, _exit都将导致整个进程终止;

b. 单个线程退出方式有三种:

  1> 线程执行函数start_rtn()中使用return返回,返回值为线程退出码;

  2> 被同一个进程的其他线程使用pthread_cancel()取消;

  3> 线程自身调用了pthread_exit();

说明:pthread_join(pthread_t tid, void **rval_ptr)函数会阻塞调用线程,直到tid线程通过上述三种方式终止退出,且return/pthread_exit()方式会设置相应线程退出码rval_ptr,而pthread_cancel()取消的线程,将退出码设置为PTHREAD_CANCELED.

 

6、 线程清理处理程序(thread cleanup handler)

a> pthread_cleanup_push()与pthread_cleanup_pop()均为<pthread.h>中实现的宏定义,具体实现如下:

?
pthread_cleanup_push and pthread_cleanup_pop are macros and must always
   be used in matching pairs at the same nesting level of braces.  */
#  define pthread_cleanup_push(routine, arg) \
  do{                                        \
    __pthread_cleanup_class __clframe (routine, arg)
  
/* Remove a cleanup handler installed by the matching pthread_cleanup_push.
   If EXECUTE is non-zero, the handler function is called. */
#  define pthread_cleanup_pop(execute) \
    __clframe.__setdoit (execute);                        \
  }while(0)

 可见push/pop中的{/}是一一对应的,因此pthread_cleanup_push/pop()也应一一对应出现,否则编译出错。

 

b> 当线程执行下列之一操作时调用清理函数,thread_cleanup_push由栈结构实现,注意清理程序调用的顺序,先入后出。

  1: 调用pthread_exit()时,而直接return不会出发清理函数;

  2: 相应取消请求pthread_cancel()时;

  3: 使用非零execute参数调用pthread_cleanup_pop()时;

尤其需注意pthread_cleanup_pop()参数不同及此语句所处位置不同而有不同效果。

看此代码实例,注意return或pthread_exit()位置不同导致pthread_cleanup_pop()不同参数的效果变化。

?
#include <pthread.h>
void testPointerSize()
{
    void*tret;
    printf("size of pointer in x86-64:%d\n",sizeof(tret));  
    //result is 8 in x86-64.
    //which is 4 in x86-32.
  
    printf("size of int in x86-64:%d\n",sizeof(int));   
    //result is 4 in x86-64.
    //which is also 4 in x86-32.
}
voidcleanup(void*arg)
{
    printf("cleanup:%s\n",(char*)arg);
}
void* thr_fn1(void*arg)
{
    printf("thread 1 start\n");
    pthread_cleanup_push(cleanup,"thread 1 first handler");
    pthread_cleanup_push(cleanup,"thread 1 second handler");
    if(arg)
        return((void*)1);//arg !=0 ,return here.
//  return here will not triger any cleanup.
    pthread_cleanup_pop(0);
    pthread_cleanup_pop(1);
    return((void*)2);//will not run this
}
void* thr_fn2(void*arg)
{
    printf("thread 2 start\n");
    pthread_cleanup_push(cleanup,"thread 2 first handler");
    pthread_cleanup_push(cleanup,"thread 2 second handler");
    pthread_cleanup_pop(0);
    pthread_cleanup_pop(1);
    return((void*)2);
//  return here can triger cleanup second handler;
}
  
void* thr_fn3(void*arg)
{
    printf("thread 3 start\n");
    pthread_cleanup_push(cleanup,"thread 3 first handler");
    pthread_cleanup_push(cleanup,"thread 3 second handler");
    if(arg)
        pthread_exit((void*)3);
    //pthread_exit() here will triger both cleanup first&second handler.
    pthread_cleanup_pop(1);
    pthread_cleanup_pop(0);
    pthread_exit((void*)3);//wont run this
}
void* thr_fn4(void*arg)
{
    printf("thread 4 start\n");
    pthread_cleanup_push(cleanup,"thread 4 first handler");
    pthread_cleanup_push(cleanup,"thread 4 second handler");
    pthread_cleanup_pop(1);
    pthread_cleanup_pop(0);
    pthread_exit((void*)4);
    //pthread_exit() here will triger cleanup second handler.
}
  
int main(void)
{
    testPointerSize();
    interr;
    pthread_t tid1, tid2, tid3, tid4;
    void*tret;
      
    err = pthread_create(&tid1, NULL, thr_fn1, (void*)1);
    err = pthread_join(tid1,&tret); 
    printf("thread 1 exit code %d\n",(int)tret);
      
    err = pthread_create(&tid2, NULL, thr_fn2, (void*)2);
    err = pthread_join(tid2, &tret);
    printf("thread 2 exit code %d\n",(int)tret);
  
    err = pthread_create(&tid3, NULL, thr_fn3, (void*)3);
    err = pthread_join(tid3,&tret); 
    printf("thread 3 exit code %d\n",(int)tret);
      
    err = pthread_create(&tid4, NULL, thr_fn4, (void*)4);
    err = pthread_join(tid4, &tret);
    printf("thread 4 exit code %d\n",(int)tret);
}

 运行结果:

?
[root@hello testData]# ./test 
size of pointer in x86-64:8
size of intin x86-64:4
thread1 start
thread1exitcode 1
thread2 start
cleanup:thread2 first handler
thread2exitcode 2
thread3 start
cleanup:thread3 second handler
cleanup:thread3 first handler
thread3exitcode 3
thread4 start
cleanup:thread4 second handler
thread4exitcode 4

  由上述测试程序总结如下:

1> push与pop间的return,将导致清理程序不被触发;

2> 位于pop之后return,由pop的参数确定是否触发清理程序,非零参数触发,零参数不触发;

3> push/pop间的pthread_exit(),将触发所有清理函数;

4>位于pop之后的pthread_exit()时,pop参数决定是否触发清理程序;

其实,上述四种情况只是测试验证了前文b所说三个条件,加深理解。

 

7、pthread_cleanup_push()/pthread_cleanup_pop()的详解

一般来说,Posix的线程终止有两种情况:正常终止和非正常终止。线程主动调用pthread_exit()或者从线程函数中return都将使线程正常退出,这是可预见的退出方式;非正常终止是线程在其他线程的干预下,或者由于自身运行出错(比如访问非法地址)而退出,这种退出方式是不可预见的。

不论是可预见的线程终止还是异常终止,都会存在资源释放的问题,在不考虑因运行出错而退出的前提下,如何保证线程终止时能顺利的释放掉自己所占用的资源,特别是锁资源,就是一个必须考虑解决的问题。

最经常出现的情形是资源独占锁的使用:线程为了访问临界资源而为其加上锁,但在访问过程中被外界取消,如果线程处于响应取消状态,且采用异步方式响应,或者在打开独占锁以前的运行路径上存在取消点,则该临界资源将永远处于锁定状态得不到释放。外界取消操作是不可预见的,因此的确需要一个机制来简化用于资源释放的编程。

在POSIX线程API中提供了一个pthread_cleanup_push()/pthread_cleanup_pop()函数对用于自动释放资源 --从pthread_cleanup_push()的调用点到pthread_cleanup_pop()之间的程序段中的终止动作(包括调用 pthread_exit()和取消点终止)都将执行pthread_cleanup_push()所指定的清理函数。API定义如下:

void pthread_cleanup_push(void (*routine) (void  *),  void *arg)void pthread_cleanup_pop(int execute)

pthread_cleanup_push()/pthread_cleanup_pop()采用先入后出的栈结构管理,void routine(void *arg)函数在调用pthread_cleanup_push()时压入清理函数栈,多次对pthread_cleanup_push()的调用将在清理函数栈中形成一个函数链,在执行该函数链时按照压栈的相反顺序弹出。execute参数表示执行到pthread_cleanup_pop()时是否在弹出清理函数的同时执行该函数,为0表示不执行,非0为执行;这个参数并不影响异常终止时清理函数的执行。

pthread_cleanup_push()/pthread_cleanup_pop()是以宏方式实现的,这是pthread.h中的宏定义:

#define pthread_cleanup_push(routine,arg)                                       { struct _pthread_cleanup_buffer _buffer;                                       _pthread_cleanup_push (&_buffer, (routine), (arg));#define pthread_cleanup_pop(execute)                                              _pthread_cleanup_pop (&_buffer, (execute)); }可见,pthread_cleanup_push()带有一个"{",而pthread_cleanup_pop()带有一个"}",因此这两个函数必须成对出现,且必须位于程序的同一级别的代码段中才能通过编译。在下面的例子里,当线程在"do some work"中终止时,将主动调用pthread_mutex_unlock(mut),以完成解锁动作。work"中终止时,将主动调用pthread_mutex_unlock(mut),以完成解锁动作。pthread_cleanup_push(pthread_mutex_unlock, (void *) &mut);pthread_mutex_lock(&mut);/* do some work */pthread_mutex_unlock(&mut);pthread_cleanup_pop(0);必须要注意的是,如果线程处于PTHREAD_CANCEL_ASYNCHRONOUS状态,上述代码段就有可能出错,因为CANCEL事件有可能在pthread_cleanup_push()和pthread_mutex_lock()之间发生,或者在pthread_mutex_unlock()和pthread_cleanup_pop()之间发生,从而导致清理函数unlock一个并没有加锁的mutex变量,造成错误。因此,在使用清理函数的时候,都应该暂时设置成PTHREAD_CANCEL_DEFERRED模式。为此,POSIX的Linux实现中还提供了一对不保证可移植的pthread_cleanup_push_defer_np()/pthread_cleanup_pop_defer_np()扩展函数,功能与以下代码段相当:{ int oldtype; pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldtype); pthread_cleanup_push(routine, arg); ... pthread_cleanup_pop(execute); pthread_setcanceltype(oldtype, NULL); }
1 0
原创粉丝点击