互斥锁和条件变量实现生产者消费者问题

   同步中有一个称为生产者-消费者问题的经典问题,也称为有界缓冲区问题。一个或多个生产者(线程或进程)

创建着一个个的数据条目,然后这些数据条目有一个或多个消费者(线程或进程)处理。数据条目在生产者和消

费者之间是使用某种类型的IPC传递的。

   而在我们的单个消费者和单个生产者之间的问题中,使用互斥锁和条件变量使其同步。而互斥锁用于上锁,条

件变量则用于等待。在程序中定义了如下的结构体:

typedef struct pc_st
{
    int buffer[BUFFER_SIZE];
    pthread_mutex_t mutex;
    pthread_cond_t notfull;
    pthread_cond_t notempty;
    int write_pos;
    int read_pos;
}pc_st;

   在结构体中定义了一个数组用于存储产品,定义了互斥变量,定义了两个条件变量,定义了两个位置,当生产

产品时和消费产品时用于判断数组中是否是满的还是空的。

   之后定义的结构体变量对其进行初始化,在程序中,主要有两个函数去实现生产和消费功能,put()函数是实现

生产者生产产品的函数,而get()函数是实现消费者进行消费产品的函数。

   下面是运用互斥锁和条件变量来实现生产者消费者问题的代码:

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#define BUFFER_SIZE 8
#define MAX_COUNT 20

typedef struct pc_st
{
    int buffer[BUFFER_SIZE];
    pthread_mutex_t mutex;
    pthread_cond_t notfull;
    pthread_cond_t notempty;
    int write_pos;
    int read_pos;
}pc_st;

#define OVER -1
#define PC_ST_INITIALIZER {{OVER,OVER,OVER,OVER,OVER,OVER,OVER,OVER},PTHREAD_MUTEX_INITIALIZER,PTHREAD_COND_INITIALIZER,PTHREAD_COND_INITIALIZER,0,0}

pc_st pc= PC_ST_INITIALIZER;

void put(int data)
{
    pthread_mutex_lock(&pc.mutex);
    if((pc.write_pos+ 1)%BUFFER_SIZE== pc.read_pos)  
        pthread_cond_wait(&pc.notfull,&pc.mutex);
    pc.buffer[pc.write_pos]= data;
    pc.write_pos= (pc.write_pos+ 1)%BUFFER_SIZE;
    pthread_cond_signal(&pc.notempty);
    pthread_mutex_unlock(&pc.mutex);
}
int get()
{
    int value;
    pthread_mutex_lock(&pc.mutex);
    if(pc.read_pos== pc.write_pos)  
        pthread_cond_wait(&pc.notempty,&pc.mutex);
    value= pc.buffer[pc.read_pos];
    pc.read_pos= (pc.read_pos+ 1)%BUFFER_SIZE;
    pthread_cond_signal(&pc.notfull);
    pthread_mutex_unlock(&pc.mutex);
    return value;
}
void* producer(void *arg)
{
    int i= 1;
    while(i<= MAX_COUNT)
    {
        put(i);
        i++;
    }
    put(OVER);
}
void* consumer(void *arg)
{
    int value;
    while(1)
    {
        value= get();
        if(value== OVER)
            break;
        printf("value= %d\n",value);
        sleep(1);
    }
}
int main()
{
    pthread_t pro_id,con_id;
    pthread_create(&pro_id,NULL,producer,NULL);
    pthread_create(&con_id,NULL,consumer,NULL);
    pthread_join(pro_id,NULL);
    pthread_join(con_id,NULL);
    return 0;
}

 

posted @ 2018-06-13 15:46  XNQC  阅读(1949)  评论(0编辑  收藏  举报