zoukankan      html  css  js  c++  java
  • Linux Pthread 深入解析(转-度娘818)

    Linux Pthread 深入解析

     

    Outline 

    - 1.线程特点

    - 2.pthread创建

    - 3.pthread终止

            - 4.mutex互斥量使用框架

            - 5.cond条件变量

            - 6.综合实例

    ================================================================================================

    1. 线程特点

    线程拥有自己独立的栈、调度优先级和策略、信号屏蔽字(创建时继承)、errno变量以及线程私有数据。进程的其他地址空间均被所有线程所共享,因此线程可以访问程序的全局变量和堆中分配的数据,并通过同步机制保证对数据访问的一致性。
     
    2. pthread创建
    pthread有一个线程ID,类型为pthread_t,在使用printf打印时,应转换为u类型。
    pthread_equal可用于比较两个id是否相等;pthread_self用于获取当前线程的ID。
    pthread_create用于创建新的线程,可以给线程传入一个void *类型的参数,例如一个结构体指针或者一个数值。
    系统并不能保证哪个线程会现运行:新创建的线程还是调用线程。
     
    3. pthread终止
    a) 从线程函数中返回
    b) 被同一进程中的其他线程取消
    c) 线程调用pthread_exit
    注意,线程的返回值需要转换为void *类型。
     
    pthread_exit(void *ret)
    pthread_join(pthread_t id, void **ret)
     
    ret均可设置为NULL
     
    4.  mutex 互斥量使用框架
    pthread_mutex_t lock;
    pthread_mutex_init 或者 PTHREAD_MUTEX_INITIALIZER(仅可用在静态变量)
    pthread_mutex_lock / pthread_mutex_unlock / pthread_mutex_trylock
    pthread_mutex_destroy
     
    5. cond 条件变量
    pthread_cond_t qready;
    pthread_mutex_t qlock;
    pthread_mutex_init 或者 PTHREAD_MUTEX_INITIALIZER
    pthread_cond_init 或者 PTHREAD_COND_INITIALIZER
    pthread_mutex_lock(&qlock...)
    pthread_cond_wait(&qready, &qlock...) / pthread_cond_timewait
    pthread_mutex_unlock(&qlock)
    pthread_cond_destroy
     
    //唤醒条件变量
    pthread_cond_signal
    pthread_cond_broadcast
     
    条件变量是pthread中比较难以理解的一点,主要会产生以下疑惑:
    Q1. 假如在调用pthread_{cond_wait | cond_timedwait}之前就调用pthread_cond_{signal | broadcast}会发生什么?
     
    Q2. pthread_cond_{cond_wait | cond_timewait}为什么需要一个已经锁住的mutex作为变量?
     
    Q3. pthread_cond_{signal | broadcast}使用之前必须获取wait中对应的mutex吗?
     
    Q4. 假如pthread_cond_{signal | broadcast}必须获取mutex,那么下列两种形式,哪种正确?为什么?
     
     1)
     lock(lock_for_X);
     change(X);
     unlock(lock_for_X);
     pthread_cond_{signal | broadcast};
     
     2)
     lock(lock_for_X);
     change(X);
     pthread_cond_{signal | broadcast};
     unlock(lock_for_X);
     
    ----思考-------思考-------思考-------思考------思考-------思考------思考------思考-------思考-------
     
    A1: 什么都不会发生,也不会出错,仅仅造成这次发送的signal丢失。
     
    A2: 一般场景如下,我们需要检查某个条件是否满足(如队列X是否为空、布尔Y是否为真),假如没有条件变量,我们唯一的选择是
     
    1. while (1) {
    2.   lock(lock_for_X);
    3.   if (is not empty) {
    4.     unlock(lock_for_X);
    5.     break;
    6.   } else { //is empty, loop continues
    7.     unlock(lock_for_X);
    8.     sleep(10);
    9.   }
    10. }
    11. //is not empty, loop ends
    12. process(X);
     
    明显这种轮询的方式非常耗费CPU时间,这时候我们很容易的想到,如果有一种机制,可以异步通知我们队列的状态发生了变化,那么我们便无须再轮询,只要等到通知到来时再检查条件是否满足即可,其他时间则将程序休眠,因此现在代码变成这样:
     
    1. while (1) {
    2.   lock(lock_for_X);
    3.   if (is not empty) {
    4.     unlock(lock_for_X);
    5.     break;
    6.   } else {
    7.     unlock(lock_for_X); //must called before my_wait(), otherwise no one can acquire the lock and make change to X
    8.     -------------------------------------->窗口,由于已经解锁,其他程序可能改变X,并且试图唤醒mywait,但在一个繁忙的系统中,可能此时my_还没被调用!
    9.     my_wait(); //go to sleep and wait for the notification
    10.   }
    11. }
     
    my_wait是一个假想的函数,作用如注释所示。
    不难发现,这样做以后,我们无须再轮询了,只需要等待my_wait()被唤醒以后检查条件是否满足。
    但 是请注意,正如图中所示,存在1个时间窗口。若其他程序在这个窗口中试图唤醒my_wait,由于此时my_wait还没有被调用,那么这个信号将丢失, 造成my_wait一直阻塞。解决的办法就是,要将unlock和my_wait合并成一个原子操作,这样就不会被其他程序插入执行。我想到这里,你应该 已经明白了,这个原子操作的函数就是pthread_cond_{signal | broadcast}.

    A3: 是的。
     
    A4: 对于1),在不同的操作系统中,可能会造成不确定的调度结果(可能会造成调度优先级反转);对于2)可以保证无论在何种操作系统中都将获得预期的调度顺序。
     
    设想一个场景:有两个消费者线程A和B,我们设定A的优先级比B高,A正在等待条件变量被出发,即已经调用了pthread_wait,并且处于阻塞状态:
     
    1. lock(lock_for_X);
    2. while (is empty) {
    3.   pthread_cond_wait(&qready, &lock_for_X);
    4. }
    5. unlock(lock_for_X);
     
    B中没有调用pthread_wait,而是做类似如下的处理:
     
    1. while(1) { 
    2.   lock(lock_for_X);
    3.   dequeue(X);
    4.   unlock(lock_for_X);
    5. }
    另一个线程C,为生产者,采用1)方案,则代码如下,先unlock,再发出signal:
     
     lock(lock_for_X);
     change(X);
     unlock(lock_for_X);
     pthread_cond_{signal | broadcast};
     
    当 发出unlock以后,发送signal之前,此时消费者B已经满足了运行条件,而消费者A虽然优先级比B高,但是由于其运行条件还需要signal,所 以不具备立刻运行的条件,此时就看操作系统如何实现调度算法了。有些操作系统,可能会因为A不具备立刻运行条件,即使它的优先级比B高,此时还是让B线程 先运行,那么,后续将分成两种情况:
     
    (a) B获得了lock,但是还没有将X队列中的刚刚加入的条目移除,此时C调用了signal,A接收到了signal,由于A的优先级高,那么A抢占B,A 从函数pthread_cond_wait返回之前需要再次将lock上锁,但是A抢占后发现,lock被人锁住了(还没有被B释放),只好再次休眠,等 待锁被释放,结果B又被唤醒,也可能因此造成A和B的死锁,这个具体要看操作系统的调度算法。
     
    (b) B获得了lock,并且执行了dequeue,然后释放了锁。此时C调用了signal,A接收到了signal,由于A的优先级高,那么A抢占B,A这 次顺利的获取了锁得以从pthread_cond_wait中返回,但是在检查条件时,却发现队列是空的,于是乎再次进入 pthread_cond_wait休眠。结果A又无法被执行,A可能由此进入饥饿状态。
     
    但是如果C采用2)方案:
     
     lock(lock_for_X);
     change(X);
     pthread_cond_{signal | broadcast};
     unlock(lock_for_X);
     
    在unlock以后,A、B都具备了立即运行的条件,由于A比B的优先级高,因此操作系统必定会先调度A执行,就避免了前面一种不确定的调度结果。
     
     
    #include <pthread.h>
    #include <unistd.h>
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
     
    static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
    static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
     
    struct node
    {
        int n_number;
        struct node *n_next;
    } *head = NULL; /*[thread_func]*/
     
    /*释放节点内存 */
    static void cleanup_handler(void *arg)
    {
        printf("Cleanup handler of second thread.
    ");
        free(arg);
        (void)pthread_mutex_unlock(&mtx);
    }
     
    static void *thread_func(void *arg)
    {
        struct node *p = NULL;
        pthread_cleanup_push(cleanup_handler, p);
         
        while (1)
        {
            pthread_mutex_lock(&mtx);
            //这个mutex_lock主要是用来保护wait等待临界时期的情况,
            //当在wait为放入队列时,这时,已经存在Head条件等待激活
            //的条件,此时可能会漏掉这种处理
            //这个while要特别说明一下,单个pthread_cond_wait功能很完善,
            //为何这里要有一个while (head == NULL)呢?因为pthread_cond_wait
            //里的线程可能会被意外唤醒,如果这个时候head != NULL,
            //则不是我们想要的情况。这个时候,
            //应该让线程继续进入pthread_cond_wait
             
            while (head != NULL)
            {
                pthread_cond_wait(&cond, &mtx);
                // pthread_cond_wait会先解除之前的pthread_mutex_lock锁定的mtx,
                //然后阻塞在等待队列里休眠,直到再次被唤醒
                //(大多数情况下是等待的条件成立而被唤醒,唤醒后,
                //该进程会先锁定先pthread_mutex_lock(&mtx);,
                // 再读取资源 用这个流程是比较清楚的
                /*block-->unlock-->wait() return-->lock*/
                 
                p = head;
                head = head->n_next;
                printf("Got %d from front of queue
    ", p->n_number);
                free(p); 
            }
            pthread_mutex_unlock(&mtx); //临界区数据操作完毕,释放互斥锁
     
        }
         
        pthread_cleanup_pop(0);
        return 0;
    }
     
    int main(void)
    {
        pthread_t tid;
        int i;
        struct node *p;
        pthread_create(&tid, NULL, thread_func, NULL);
        //子线程会一直等待资源,类似生产者和消费者,
        //但是这里的消费者可以是多个消费者,
        //而不仅仅支持普通的单个消费者,这个模型虽然简单,
        //但是很强大
        for (i = 0; i < 10; i++)
        {
            p = (struct node *)malloc(sizeof(struct node));
            p->n_number = i;
            pthread_mutex_lock(&mtx); //需要操作head这个临界资源,先加锁,
            p->n_next = head;
            head = p;
            pthread_cond_signal(&cond);
            pthread_mutex_unlock(&mtx); //解锁
            sleep(1);
        }
        printf("thread 1 wanna end the cancel thread 2.
    ");
        pthread_cancel(tid);
        //关于pthread_cancel,有一点额外的说明,它是从外部终止子线程,
        //子线程会在最近的取消点,退出线程,而在我们的代码里,最近的
        //取消点肯定就是pthread_cond_wait()了。
        pthread_join(tid, NULL);
        printf("All done -- exiting
    ");
        return 0; 
    }
     
    6. 综合实例
    1. /*
    2.  * =====================================================================================
    3.  *
    4.  * Filename: pthread.c
    5.  *
    6.  * Description:
    7.  *
    8.  * Version: 1.0
    9.  * Created: 08/17/11 11:06:35
    10.  * Revision: none
    11.  * Compiler: gcc
    12.  *
    13.  * Author: YOUR NAME (),
    14.  * Company:
    15.  *
    16.  * =====================================================================================
    17.  */
    18. #include <stdio.h>
    19. #include <pthread.h>
    20. #include <error.h>
    21. #include <stdlib.h>
    22. #include <unistd.h>
    23. #include <string.h>
    24. pthread_cond_t qready;
    25. pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER;
    26. struct foo {
    27.     int cnt;
    28.     pthread_mutex_t f_lock;
    29. };
    30. void cleanup(void *arg)
    31. {
    32.     printf("clean up: %s ", (char *)arg);
    33. }
    34. void printids(char *str)
    35. {
    36.     printf("%s pid = %u tid = %u / 0x%x ",
    37.             str, (unsigned int)getpid(), (unsigned int)pthread_self(), (unsigned int)pthread_self());
    38. }
    39. void *thread1(void *arg)
    40. {
    41.     pthread_mutex_lock(&qlock);
    42.     pthread_cond_wait(&qready, &qlock);
    43.     pthread_mutex_unlock(&qlock);
    44.     printids("thread1:");
    45.     
    46.     pthread_cleanup_push(cleanup, "thread 1 first cleanup handler");
    47.     pthread_cleanup_push(cleanup, "thread 1 second cleanup handler");
    48.     printf("thread 1 push complete! ");
    49.     
    50.     pthread_mutex_lock(&((struct foo *)arg)->f_lock);
    51.     ((struct foo *)arg)->cnt;
    52.     printf("thread1: cnt = %d ", ((struct foo *)arg)->cnt);
    53.     pthread_mutex_unlock(&((struct foo *)arg)->f_lock);
    54.     if (arg)
    55.         return ((void *)0);
    56.     
    57.     pthread_cleanup_pop(0);
    58.     pthread_cleanup_pop(0);
    59.     pthread_exit((void *)1);
    60. }
    61. void *thread2(void *arg)
    62. {
    63.     int exit_code = -1;
    64.     printids("thread2:");
    65.     
    66.     printf("Now unlock thread1 ");
    67.     pthread_mutex_lock(&qlock);
    68.     pthread_mutex_unlock(&qlock);
    69.     pthread_cond_signal(&qready);
    70.     printf("Thread1 unlocked ");
    71.     pthread_cleanup_push(cleanup, "thread 2 first cleanup handler");
    72.     pthread_cleanup_push(cleanup, "thread 2 second cleanup handler");
    73.     printf("thread 2 push complete! ");
    74.     
    75.     if (arg)
    76.         pthread_exit((void *)exit_code);
    77.     pthread_cleanup_pop(0);
    78.     pthread_cleanup_pop(0);
    79.     
    80.     pthread_exit((void *)exit_code);
    81. }
    82. int main(int argc, char *argv[])
    83. {
    84.     int ret;
    85.     pthread_t tid1, tid2;
    86.     void *retval;
    87.     struct foo *fp;
    88.     ret = pthread_cond_init(&qready, NULL);
    89.     if (ret != 0) {
    90.         printf("pthread_cond_init error: %s ", strerror(ret));
    91.         return -1;
    92.     }
    93.     if ((fp = malloc(sizeof(struct foo))) == NULL) {
    94.         printf("malloc failed! ");
    95.         return -1;
    96.     }
    97.     if (pthread_mutex_init(&fp->f_lock, NULL) != 0) {
    98.         free(fp);
    99.         printf("init mutex failed! ");
    100.     }
    101.     pthread_mutex_lock(&fp->f_lock);
    102.     ret = pthread_create(&tid1, NULL, thread1, (void *)fp);
    103.     if (ret != 0) {
    104.         printf("main thread error: %s ", strerror(ret));
    105.         return -1;
    106.     }
    107.     ret = pthread_create(&tid2, NULL, thread2, (void *)1);
    108.     if (ret != 0) {
    109.         printf("main thread error: %s ", strerror(ret));
    110.         return -1;
    111.     }
    112.     
    113.     ret = pthread_join(tid2, &retval);
    114.     if (ret != 0) {
    115.         printf("pthread join falied! ");
    116.         return -1;
    117.     }
    118.     else
    119.         printf("thread2 exit code %d ", (int)retval);
    120.     fp->cnt = 1;
    121.     printf("main thread: cnt = %d ",fp->cnt);
    122.     pthread_mutex_unlock(&fp->f_lock);
    123.     sleep(1);    //there is no guarantee the main thread will run before the newly created thread, so we wait for a while
    124.     printids("main thread:");
    125.     printf("Press <RETURN> to exit ");
    126.     ret = pthread_cond_destroy(&qready);
    127.     if (ret != 0) {
    128.         printf("pthread_cond_destroy error: %s ", strerror(ret));
    129.         return -1;
    130.     }
    131.     getchar();
    132.     return 0;
    133. }
  • 相关阅读:
    七easy网络陷阱上当
    移动端--web开展
    ContentType是否大小写区分?
    NYOJ 24 素数的距离问题
    Emoji:搜索将与您找到表情符号背后的故事
    Cocos2d-X之LUA注意事项
    [Angular] ChangeDetection -- onPush
    [Node.js] Build microservices in Node.js with micro
    [Angular] Scrolling the Message List To the Bottom Automatically Using OnChanges
    [Angular] Ngrx/effects, Action trigger another action
  • 原文地址:https://www.cnblogs.com/sanchrist/p/3573511.html
Copyright © 2011-2022 走看看