生产者消费者问题与条件变量

条件变量与互斥锁的优势在于条件变量能够减少竞争的次数, 如下例子中所示,当head为空时,消费者线程阻塞在pthread_cond_wait , 这时生产这能够直接获得锁,而不用与消费者线程竞争.

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

using namespace std;

typedef struct pie
{
        int idx;
        struct pie *next;
} PID, *PPIE;

PPIE head = NULL;
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void *thread_fun(void *arg)
{
        while(1)
        {
                pthread_mutex_lock(&mtx);
                while (head == NULL)
                {
                        pthread_cond_wait(&cond, &mtx);
                }
                PPIE p = head;
                head = head->next;
                p->next = NULL;
                printf("========>consumer %ld %d\n", reinterpret_cast<long>(arg), p->idx);
                free(p);
                pthread_mutex_unlock(&mtx);
                usleep(rand()%500000);
        }
    
        return NULL;
}

int main(int argc, char *argv[])
{

        pthread_t thread;
        srand(1000);
        for (long i=0; i<5; i++)
        {
        	int ret = pthread_create(&thread, NULL,
                          thread_fun, (void*)i);
        	if (ret != 0)
        	{
                printf("pthread_create error\n");
                return 1;
        	}
        	pthread_detach(thread);
        }

        while(1)
        {
                PPIE p = (PPIE)malloc(sizeof(struct pie));
                if (p)
                {
                        pthread_mutex_lock(&mtx);
                        p->idx = rand()%1000;
                        p->next = head;
                        head = p;
                        printf("===========>productor %d\n", p->idx);
                        pthread_cond_signal(&cond);
                        pthread_mutex_unlock(&mtx);
                        usleep(rand()%100000);
                }
        }
        return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值