生产者和消费者模型

条件变量:可以引起阻塞,并非锁,要和互斥量组合使用
超时等待
int pthread_cond_timedwait(pthread_cond_t *restrict cond,pthread_mutex_t *restrict mutex,const struct timespec *restrict abstime);

struct timesec{
time_t tv_sec; //秒,绝对时间,填写的时候time(NULL)+600设置超时600s
long tv_nsec; //纳秒
}

条件变量阻塞等待
int pthread_cond_wait(pthread_cond_t *restrict cond,pthread_mutex_t *restrict mutex);
先释放mutex
阻塞在cond条件变量上

销毁一个条件变量
int pthread_cond_destroy(pthread_cond_t *cond);
初始化一个条件变量
int pthread_cond_init(pthread_cond_t *restrict cond,const pthread_condattr_t *restrict attr);
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;

至少唤醒一个阻塞在条件变量cond上的线程
int pthread_cond_signal(pthread_cond_t *cond);
唤醒阻塞在条件变量cond上的全部线程
int pthread_cond_broadcast(pthread_cond_t *cond);

条件变量:避免没有必要的竞争

cond_product.c


#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>

pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;

int beginnum=100;

typedef struct _ProdInfo{
    int num;
    struct _ProdInfo *next;
}ProdInfo;

ProdInfo *Head=NULL;

void* thr_producter(void *arg)
{
    //负责在链表中添加数据
    while(1){
        ProdInfo *prod=malloc(sizeof(ProdInfo));
        prod->num=beginnum++;
        printf("----%s----self=%lu----%d\n",__FUNCTION__,pthread_self(),prod->num);
        pthread_mutex_lock(&mutex);
        //加入链表
        prod->next=Head;
        Head=prod; 
        pthread_mutex_unlock(&mutex);
        //发起通知
        pthread_cond_signal(&cond);
        sleep(rand()%4);
    }
    return NULL}     

void* thr_customer(void *arg)
{
    ProdInfo *prod=NULL;
    while(1){
        //取链表的数据
        pthread_mutex_lock(&mutex);
        while(Head==NULL){
            pthread_cond_wait(&cond,&mutex); // 在此之前必须加锁
        }
        prod=Head;
        Head=Head->next;
        printf("----%s----self=%lu----%d\n",__FUNCTION__,pthread_self(),prod->num);
        pthread_mutex_unlock(&mutex);
        sleep(rand()%2);
        free(prod);
    }
    return NULL}   

int main()
{
    pthread_t tid[2];
    pthread_create(&tid[0],NULL,thr_producter,NULL);
    pthread_create(&tid[1],NULL,thr_customer,NULL);
    pthread_create(&tid[2],NULL,thr_customer,NULL);

    pthread_join(tid[0],NULL);
    pthread_join(tid[1],NULL);
    pthread_join(tid[2],NULL);
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

给算法爸爸上香

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值