• 生产者消费者-(多线程同步和互斥)


    条件变量是利用线程间共享的全局变量进行同步的一种机制,主要包括两个动作:一个线程等待条件变量的条件成立而挂起(此时不再占用cpu);另一个线程使条件成立(给出条件成立信号)。为了防止竞争,条件变量的使用总是和一个互斥锁结合在一起。

    /* 等待条件 */
    /* 注意:pthread_cond_wait为阻塞函数。解开锁,再等待。等条件满足时,需要抢到锁,才可以被唤醒*/    
    pthread_cond_wait(&cond_pro,&mutex); 
    
    /* 激发条件 */
    /* 所有因为不满足条件的线程都会阻塞在条件变量cond_pro中的一个队列中 */
    /* 以广播方式,通知所有被阻塞的所有线程 */
    pthread_cond_broadcast(&cond_pro);
    /* 以signal方式,只通知排在最前面的线程 */
    pthread_cond_signal(&cond_pro);
    复制代码
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <pthread.h>
    #include <unistd.h>
    #define CELL 10
    #define FLORE 0
    
    
    
    int i = 0; /* 所有线程共享的全局变量,此处假定至多递增至10,最小减到0 */
    
    pthread_mutex_t mutex;              /* 定义互斥锁 */
    pthread_cond_t cond_pro, cond_con;  /* 定义两个条件变量 */
    
    /* 生产者线程 */
    void* pro_handler(void *arg)
    {
        pthread_detach(pthread_self());   /* 由系统回收线程资源,而非主线程回收资源 ,此类情况主线程是个服务器,永久不会退出 */
        
        while(1)
        {
            pthread_mutex_lock(&mutex);
            while(i >= CELL)
            {
                pthread_cond_wait(&cond_pro,&mutex); 
                /* continue是轮询,此处是阻塞 */
                /* 把锁放开再等 ,第一个参数是结构体指针,其中有成员存放被阻塞的函数 */
                /*不占cpu*/
                /* 不满足条件时才会等 ,需要别人告诉它,才能唤醒它*//* 当它返回时,锁也要回来了*/
            }
            i++;
            if(i == 1)
            {
                /* 由空到不空,唤醒消费者 */
                pthread_cond_signal(&cond_con);    /*不会立马signal被阻塞的消费者线程,因为其还要等锁抢回来*/
            }
            printf("add i: %d 
    ", i);
            pthread_mutex_unlock(&mutex);
            sleep(rand() % 5 + 1);
        }
    }
    
    /* 消费者线程 */
    void* con_handler(void *arg)
    {
        pthread_detach(pthread_self());
        while(1)
        {
            pthread_mutex_lock(&mutex);
            while(i <= FLORE)
            {
                pthread_cond_wait(&cond_cno,&mutex);
            }
            i--;
            if(i == 9) /* 由满到不满,要告诉生产者,以便将其唤醒 *//*此处,直接signal也可以,我们是为了更加精确*/
            {
                pthread_cond_signal(&cond_pro);
            }
            printf("con i: %d 
    ", i);
            pthread_mutex_unlock(&mutex);
            sleep(rand() % 5 + 1);
        }
    }
    
    int main(int argc, char *argv[]) // exe +num -num
    {
        srand(getpid());
        int con_cnt, pro_cnt;
        pro_cnt = atoi(argv[1]);
        con_cnt = atoi(argv[2]);
        pthread_mutex_init(&mutex,NULL);
        pthread_cond_init(&cond_pro,NULL);
        pthread_cond_init(&cond_con,NULL);
        pthread_t *arr = (pthread_t*)calloc(con_cnt + pro_cnt , sizeof(pthread_t));
        int index = 0;
        while(pro_cnt > 0)
        {
            pthread_create(arr + index, NULL, pro_handler, NULL);
            index++;
            pro_cnt--;
        }
        while(con_cnt > 0)
        {
            pthread_create(arr + index, NULL, con_handler, NULL);
            index++;
            con_cnt--;
        }
        while(1);
        pthread_mutex_destroy(&mutex);
        pthread_cond_destroy(&cond_pro);
        pthread_cond_destroy(&cond_con);
        return 0;
    }
    无论是在生产者线程,还是在消费者线程中。标记黄色部分的判断条件必须用while。以生产者线程举例,当i>=CELL时,也就是i满时,此时执行pthread_cond_wait(&cond_cno,&mutex); 该生产者线程被挂起。必须等到消费者线程pthread_cond_signal(&cond_pro); 将其唤醒。但是消费者将其signal还不够,被挂其的生产者线程必须重新拿到锁,才可以被激活。但是,由于在消费者signal的同时,生产者并不能立即抢到锁,所以此时可能i值又改变变为大于等于10了。因此必须用while。不然可能导致i>10。

    将生产者消费者模型进一步修改、

    生产者和消费者(互斥与同步)。资源用队列模拟(要上锁,一个时间只能有一个线程操作队列)。

    m个生产者。拿到锁,且产品不满,才能生产。当产品满,则等待,等待消费者唤醒。当产品由空到不空,通知消费者。
    n个消费者。拿到锁,且有产品,才能消费。当产品空,则等待,等待生产者唤醒。当产品由满到不满,通知生产者。
        
    生产者条件:队列不满
    消费者条件:队列不空
    因此有两个条件变量。

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <pthread.h>
    #include <unistd.h>
    #define CNT 20           /* 最多生产20个产品 */
    
    /* 用队列模拟车间 */
    /* front和tail初始化均为0,tail是下一个资源生成的下一个数组空间下标 */
    typedef struct tag
    {
        int s_arr[CNT + 1] ;   /* 生产20个产品,必须有21个空间,因为如果空间都装满产品,无法区别队列满和队列空 */
        int s_front ;
        int s_tail ;
    }QUEUE,*pQUEUE ;
    QUEUE my_que ;
    /* 资源为空 */
    int que_empty(pQUEUE pq)
    {
        return pq ->s_front == pq -> s_tail ;
    }
    /* 资源为满 */
    int que_full(pQUEUE pq)
    {
        return  (pq -> s_tail + 1)% (CNT+1) == pq -> s_front ;
    }
    int que_cnt(pQUEUE pq)
    {
        return (pq -> s_tail  - pq ->s_front + CNT + 1)% (CNT + 1) ;
    }
    pthread_mutex_t  mutex ;
    pthread_cond_t cond_pro, cond_con ;
    
    void* pro_handler(void* arg)
    {
        pthread_detach(pthread_self());
        while(1)
        {
            pthread_mutex_lock(&mutex) ;
            while(que_full(&my_que))
            {
                pthread_cond_wait(&cond_pro, &mutex);
            }
            my_que.s_arr[my_que.s_tail ] = rand() % 1000 ;
            my_que.s_tail  = (my_que.s_tail + 1)% (CNT + 1) ;
            if(que_cnt(&my_que) == 1)
            {
                pthread_cond_broadcast(&cond_con);
            }
            printf("produce a product, total num : %d 
    ", que_cnt(&my_que));
            pthread_mutex_unlock(&mutex);
            sleep(rand()%3 + 1);
        }
    }
    void* con_handler(void* arg)
    {
        pthread_detach(pthread_self());
        while(1)
        {
            pthread_mutex_lock(&mutex);
            while(que_empty(&my_que))
            {
                pthread_cond_wait(&cond_con, &mutex);
            }
            my_que.s_front = (my_que.s_front + 1) % (CNT + 1) ;
            if(que_cnt(&my_que) == CNT - 1)
            {
                /*由于我们的主线程是等消费者线程创建完之后,再创建生产者线程,
                  因此一开始所有消费者线程都会挂起,在条件变量cond_pro的队列里排队
                  因此需要用broadcast通知所有消费者线程。
                  不然一次就通知一个生产者线程,就此消费者线程会抢锁。
                  当然,如果一开始主线程先创建生产者线程,再创建消费者线程,
                  由于生产者线程不会全部阻塞,因此可以使用signal来唤醒一个        */
                pthread_cond_broadcast(&cond_pro);
            }
            printf("consume a product, total num: %d 
    ", que_cnt(&my_que));
            pthread_mutex_unlock(&mutex);
            sleep(rand()%3 + 1);
        }
    
    }
    int main(int argc, char* argv[])//exe pro_num  con_num
    {
        int con_cnt , pro_cnt ;
        my_que.s_front = 0 ; 
        my_que.s_tail = 0 ;
        pro_cnt = atoi(argv[1]) ;
        con_cnt = atoi(argv[2]) ;
        srand(getpid());
        pthread_mutex_init(&mutex, NULL);
        pthread_cond_init(&cond_pro, NULL);
        pthread_cond_init(&cond_con, NULL);
        pthread_t* arr = (pthread_t*)calloc(con_cnt + pro_cnt, sizeof(pthread_t));
        int index = 0 ;
        while(con_cnt > 0)
        {
            pthread_create(arr + index , NULL, con_handler, NULL);
            index ++ ;
            con_cnt -- ;
        }
        sleep(5);
        while(pro_cnt > 0)
        {
            pthread_create(arr + index , NULL, pro_handler, NULL);
            index ++ ;
            pro_cnt -- ;
        }
        while(1) ;
        pthread_mutex_destroy(&mutex);
        pthread_cond_destroy(&cond_pro);
        pthread_cond_destroy(&cond_con);
        return 0 ;
    }

    makefile
    main:main.c
        gcc -o $@ $< -lpthread



  • 相关阅读:
    【转载】Linux小白最佳实践:《超容易的Linux系统管理入门书》(连载六)Linux的网络配置
    Linux小白最佳实践:《超容易的Linux系统管理入门书》(连载五)Linux系统的对话方式
    Linux小白最佳实践:《超容易的Linux系统管理入门书》(连载四)本地或远程登录Linux
    【转载】Linux小白福利:《超容易的Linux系统管理入门书》(三)在虚拟机上安装Linux
    常用快递API及快递在线下单API分享
    浅谈PHP与手机APP开发即API接口开发
    身份证实名认证接口调用实例(PHP)
    Android 开发程序员必备网站
    调用聚合数据新闻头条API
    高效率完成工作的12种热门编程语言,你会用几个?
  • 原文地址:https://www.cnblogs.com/hxjbc/p/3962223.html
Copyright © 2020-2023  润新知