线程生产者和消费者

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <pthread.h>
 
 
int h= 0;
 

 
// 线程同步 - 互斥锁
pthread_mutex_t mutex;
// 阻塞线程 - 条件变量类型的变量
pthread_cond_t cond;
 
// 生产者
void* producer(void* arg)
{
   while(1)
    {
       
 
        // 使用互斥锁保护共享数据
        pthread_mutex_lock(&mutex);
 
       h = 8;

        printf("====== produce: %d\n",h);
        pthread_mutex_unlock(&mutex);
 
        // 通知阻塞的消费者线程,解除阻塞
        pthread_cond_signal(&cond);
 
        sleep(rand() % 3);
    }
    return NULL;
}
 
void* customer(void* arg)
{
    while(1)
    {
        pthread_mutex_lock(&mutex);
        // 判断链表是否为空
        if(h == 0)
        {
            // 线程阻塞
            // 该函数会对互斥锁解锁
            pthread_cond_wait(&cond, &mutex);
            // 解除阻塞之后,对互斥锁做加锁操作
        }
       
        h=0;
        printf("------ customer: %d\n",h);
         
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}
 
int main(int argc, const char* argv[])
{
    pthread_t p1, p2;
    // init
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);
 
    // 创建生产者线程
    pthread_create(&p1, NULL, producer, NULL);
    // 创建消费者线程
    pthread_create(&p2, NULL, customer, NULL);
 
    // 阻塞回收子线程
    pthread_join(p1, NULL);
    pthread_join(p2, NULL);
 
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);
 
    return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值