zoukankan      html  css  js  c++  java
  • (转载)Posix多线程编程—线程基础(2)

    (转载)http://www.cnblogs.com/yc_sunniwell/archive/2010/06/23/1763310.html

    6.名称:pthread_detach
        功能:使线程进入分离状态。
        头文件:#include <pthread.h>
        函数原形:int pthread_detach(pthread_t tid);
        参数:
        返回值:若成功则返回0,否则返回错误编号。 
        在默认情况下,线程的终止状态会保存到对该线程调用pthread_join,如果线程已经处于分离状态,线程的底层存储资源可以在线程终止时立即被收回。当线程被分离时,并不能用pthread_join函数等待它的终止状态。对分离状态的线程进行pthread_join的调用会产生失败,返回EINVAL.pthread_detach调用可以用于使线程进入分离状态。
    7.名称:pthread_cancel
        功能:取消同一进程中的其他线程
        头文件:#include <pthread.h>
        函数原形:int pthread_cancel(pthread_t tid);
        参数:tid 线程id 
        返回值:若成功返回0,否则返回错误编号。
        在默认的情况下,pthread_cancel函数会使由tid标识的线程的行为表现为如同调用了参数为PTHEAD_CANCELED的pthread_exit函数,但是,线程可以选择忽略取消方式和控制取消方式。pthread_cancel并不等待线程终止,它仅仅提出请求
    8.名称:pthread_cancel_push/ pthread_cancel_push_pop
        功能:线程清理处理程序
        头文件:#include <pthread.h>
        函数原形:void pthread_cancel_push(void (*rtn)(void *),void *arg);
                  void pthread_cancel_pop(int execute);
        参数:rtn 处理程序入口地址, arg 传递给处理函数的参数
        返回值:无 
        线程可以安排它退出时需要调用的函数,这样的函数称为线程清理处理程序,线程可以建立多个清理处理程序。处理程序记录在栈中,也就是说它们的执行顺序与它们注册时的顺序相反。
        要注意如果线程是通过从他的启动例程中返回而终止的,它的处理程序就不会调用。还要注意清理处理程序是按照与它们安装时相反的顺序调用的。

    #include <pthread.h>
    #include <stdio.h>
    
    void cleanup(void *arg)
    {
        printf(“cleanup: %s\n”,(char *)arg);
    }
    
    void *thr_fn(void *arg) /*线程入口地址*/
    {
        printf(“thread start\n”);
        pthread_cleanup_push(cleanup,”thread first handler”);/*设置第一个线程处理程序*/
        pthread_cleanup_push(cleanup,”thread second handler”); /*设置第二个线程处理程序*/
        printf(“thread push complete\n”);
        pthread_cleanup_pop(0); /*取消第一个线程处理程序*/
        pthread_cleanup_pop(0); /*取消第二个线程处理程序*/
    }
    
    int main()
    {
        pthread_t tid;
        void *tret;
    
        pthread_creat(&tid,NULL,thr_fn,(void *)1); /*创建一个线程*/
        pthread_join(tid,&tret); /*获得线程终止状态*/
    
        printf(“thread exit code %d\n”,(int)tret);
        return 0;
    }

    八、一次性初始化
        有时候我们需要对一些posix变量只进行一次初始化,如线程键(我下面会讲到)。如果我们进行多次初始化程序就会出现错误。
        在传统的顺序编程中,一次性初始化经常通过使用布尔变量来管理。控制变量被静态初始化为0,而任何依赖于初始化的代码都能测试该变量。如果变量值仍然为0,则它能实行初始化,然后将变量置为1。以后检查的代码将跳过初始化。
        但是在多线程程序设计中,事情就变的复杂的多。如果多个线程并发地执行初始化序列代码,2个线程可能发现控制变量为0,并且都实行初始话,而该过程本该仅仅执行一次。初始化的状态必须由互斥量保护。
        如果我们需要对一个posix变量静态的初始化,可使用的方法是用一个互斥量对该变量的初始话进行控制。但有时候我们需要对该变量进行动态初始化,pthread_once就会方便的多
    9.名称:pthread_once
        功能:一次性初始化
        头文件:#include <pthread.h>
        函数原形:pthread_once_t once_control=PTHREAD_ONCE_INIT;
                  int pthread_once(pthread_once_t *once_control,void(*init_routine)(void));
        参数:once_control 控制变量, init_routine 初始化函数
        返回值:若成功返回0,若失败返回错误编号。
        类型为pthread_once_t的变量是一个控制变量。控制变量必须使用PTHREAD_ONCE_INIT宏静态地初始化
        pthread_once函数首先检查控制变量,判断是否已经完成初始化,如果完成就简单地返回;否则,pthread_once调用初始化函数,并且记录下初始化被完成。如果在一个线程初始时,另外的线程调用pthread_once,则调用线程等待,直到那个现成完成初始话返回。
        下面就是该函数的程序例子:

    #include <pthread.h>
    
    pthread_once_t once = PTHREAD_ONCE_INIT;
    pthread_mutex_t mutex; /*互斥量,我们后面会讲到*/
    
    void once_init_routine(void) /*一次初始化函数*/
    {
        int status;
        status = pthread_mutex_init(&mutex, NULL);  /*初始化互斥量*/
        if (status == 0)
            printf("Init success!,My id is %u", pthread_self());
    }
    void *child_thread(void *arg)
    {
        printf("I’m child ,My id is %u", pthread_self());
        pthread_once(&once,once_init_routine);  /*子线程调用一次性初始化函数*/
    }
    int main(int argc,char *argv[ ])
    {
        pthread_t child_thread_id;
        pthread_create(&child_thread_id, NULL, child_thread, NULL);  /*创建子线程*/
    
        printf("I’m father,my id is %u", pthread_self());
        pthread_once(&once_block, once_init_routine);  /*父线程调用一次性初始化函数*/
        pthread_join(child_thread_id, NULL);
    
        return 0;
    }

    程序运行结果如下:
    ./once
    I’m father,My id is 3086874304
    Init success!,My id is 3086874304
    I’m child, My id is 3086871472  
    从上面的结果可以看到当主函数初始化成功后,子函数初始化失败
    九、线程的私有数据
        在进程内的所有线程共享相同的地址空间,任何声明为静态或外部的变量,或在进程堆声明的变量,都可以被进程所有的线程读写。那怎样才能使线程序拥有自己的私有数据呢。posix提供了一种方法,创建线程键
    10.名称:pthread_key_create
        功能:建立线程私有数据键
        头文件:#include <pthread.h>
        函数原形:int pthread_key_create(pthread_key *key,void(*destructor)(void *));
        参数:key 私有数据键, destructor 清理函数
        返回值:若成功返回0,若失败返回错误编号。
        第一个参数为指向一个键值的指针,第二个参数指明了一个destructor函数(清理函数)如果这个参数不为空,那么当每个线程结束时,系统将调用这个函数来释放绑定在这个键上的内存块这个函数常和函数pthread_once一起使用,为了让这个键只被创建一次。函数pthread_once声明一个初始化函数,第一次调用pthread_once时它执行这个函数,以后的调用将被它忽略。
    下面是程序例子:

    #include <pthread.h>
    
    pthread_key_t tsd_key;
    pthread_once_t key_once = PTHREAD_ONCE_INIT;
    
    void once_routine(void)
    {
        int status;
        status = pthread_key_create(&tsd_key, NULL);  /*初始化线程私有数据键*/
        if (status == 0)
            printf("Key create success! My id is %u\n", pthread_self());
    }
    void *child_thread(void *arg)
    {
        printf("I’m child,My id is %u\n", pthread_self());
        pthread_once(&key_once,once_routine);  /* 调用一次性初始化函数*/
    }
    int main(int argc,char *argv[ ])
    {
        pthread_t child_thread_id;
        pthread_create(&child_thread_id, NULL, child_thread, NULL);
    
        printf("I’m father,my id is%u\n", pthread_self());
        pthread_once(&key_once, once_routine);
    
        return 0;
    }

    程序运行结果如下:
    I’m father,My id is 3086231232
    Key create success! My id is 3086231232
    I’m child,My id is 2086228400

    11.名称:pthread_getspecific
        功能:读取或设置线程特定数据
        头文件:#include <pthread.h>
        函数原形:void *pthread_getspecific(pthread_key_t key);
                  int pthread_setspecific(pthread_key_t key, const void *value); 
        参数:key 私有数据键
        返回值:pthread_setspecific() 在成功完成之后返回零,其他任何返回值都表示出现了错误;pthread_getspecific 不返回任何错误。

    #include <stdio.h>
    #include <stdlib.h>
    #include <pthread.h>
    
    pthread_key_t key;
    struct test_struct {
        int i;
        float k;
    };
    void *child1 (void *arg)
    {
        struct test_struct struct_data;
        struct_data.i = 10;
        struct_data.k = 3.1415;
    
        pthread_setspecific(key, &struct_data);
        printf ("结构体struct_data的地址为 0x%p\n", &(struct_data));
        printf ("child1 中 pthread_getspecific(key)返回的指针为:0x%p\n", (struct test_struct *)pthread_getspecific(key));
        printf ("利用 pthread_getspecific(key)打印 child1 线程中与key关联的结构体中成员值:\nstruct_data.i:%d\nstruct_data.k: %f\n", \
    ((struct test_struct *)pthread_getspecific (key))->i, ((struct test_struct *)pthread_getspecific(key))->k); printf ("------------------------------------------------------\n"); } void *child2 (void *arg) { int temp = 20; sleep(2); printf ("child2 中变量 temp 的地址为 0x%p\n", &temp); pthread_setspecific (key, &temp); printf ("child2 中 pthread_getspecific(key)返回的指针为:0x%p\n", (int *)pthread_getspecific(key)); printf ("利用 pthread_getspecific(key)打印 child2 线程中与key关联的整型变量temp 值:%d\n", *((int *)pthread_getspecific(key))); } int main (void) { pthread_t tid1, tid2; pthread_key_create (&key, NULL); pthread_create (&tid1, NULL, (void *)child1, NULL); pthread_create (&tid2, NULL, (void *)child2, NULL); pthread_join (tid1, NULL); pthread_join (tid2, NULL); pthread_key_delete (key); return (0); }

    运行与输出:./pthread_key 
    结构体struct_data的地址为 0x0xb7699388
    child1 中 pthread_getspecific(key)返回的指针为:0x0xb7699388
    利用 pthread_getspecific(key)打印 child1 线程中与key关联的结构体中成员值:
    struct_data.i:10
    struct_data.k: 3.141500
    ------------------------------------------------------
    child2 中变量 temp 的地址为 0x0xb6e9838c
    child2 中 pthread_getspecific(key)返回的指针为:0x0xb6e9838c
        由输出可见,pthread_getspecific() 返回的是与key 相关联数据的指针。需要注意的是,在利用这个返回的指针时,它首先是 void 类型的,它虽然指向关联的数据地址处,但并不知道指向的数据类型,所以在具体使用时,要对其进行强制类型转换。
        其次,两个线程对自己的私有数据操作是互相不影响的。也就是说哦,虽然 key 是同名且全局,但访问的内存空间并不是相同的一个。key 就像是一个数据管理员,线程的私有数据只是到他那去注册,让它知道你这个数据的存在。

  • 相关阅读:
    生命中的另一口井
    sqlldr使用小记
    字节单位介绍
    《Java虚拟机》随笔记01
    Python生成器实现杨辉三角打印
    什么是递归?用十进制转二进制的Python函数示例说明
    Python的filter与map内置函数
    Python内置函数property()使用实例
    Python装饰器的理解
    Python迭代与递归方法实现斐波拉契数列
  • 原文地址:https://www.cnblogs.com/Robotke1/p/3056350.html
Copyright © 2011-2022 走看看