作业三:互斥锁,无名信号量,条件变量再联系一遍。

#include<myhead.h>


pthread_mutex_t fastmutex;//定义互斥锁
pthread_cond_t cond;//定义条件变量
#define MAX 5
void *product_fun(void *arg)
{

    while(1)
    {
    
        sleep(1);
        printf("生产一个苹果\n");
        pthread_cond_signal(&cond);//唤醒一个线程
    
    }
    pthread_exit(NULL);
}
void *customer_fun(void *arg)
{
    int i = 0;
    while(i<MAX){
        pthread_mutex_lock(&fastmutex);//上互斥锁
        pthread_cond_wait(&cond,&fastmutex);//等待线程被唤醒:
        printf("我买一个苹果\n");
        
        pthread_mutex_unlock(&fastmutex);
        i++;
    }
    pthread_exit(NULL);

}

int main(int argc, const char *argv[])
{
    pthread_mutex_init(&fastmutex,NULL);//初始化锁
    pthread_cond_init(&cond,NULL);//初始化条件变量
    
    
    pthread_t product,customer[MAX];
    if(pthread_create(&product,NULL,product_fun,NULL)!=0)
    {
    
        perror("create");
        return -1;
    
    }
    int i = 0;
    while(i<MAX){
        if(pthread_create(&customer[i],NULL,customer_fun,NULL)!=0)
        {
    
            perror("create");
            return -1;
        }
        i++;
    }
    i =0;
    while(i<MAX)
    {
        pthread_join(customer[i],NULL);
    }
    pthread_join(product,NULL);
    pthread_mutex_destroy(&fastmutex);
    pthread_cond_destroy(&cond);
    return 0;
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值