6.28作业

该代码示例展示了使用POSIX线程库(pthread)实现的一个简单的生产者消费者模型。生产者线程生成跑车并唤醒所有等待的消费者线程,而消费者线程在获得互斥锁后消费跑车。每个消费者线程在消费后会释放锁。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<myhead.h>
phtread_cond_t cond;//定义条件变量
phtread_mutex_t mutex;//定义互斥锁
void *task1(void *arg)//常见生产者线程
{
    while(1)
    {
        sleep(3);
        printf("我生产了一辆跑车\n");
        //pthread_cond_signal(&cond); //唤醒队列中下一个等待线程
        pthread_cond_broadcast(&cond);//唤醒队列中的所有等待线程
    }
}
void *task2(void *arg)//创建消费者线程
{
    while(1)
    {
     sleep(1);
     phtread_mutex_lock(&mutex);//上锁
     pthread_cond_wait(&cond,&mutex);//申请资源
     printf("%#ld:我消费一辆跑车\n",pthread_self());
     phtread_mutex_unlock(&mutex);//解锁
    }
}
void *task3(void *arg)//创建消费者线程
{
    while(1)
    {
     sleep(1);
     phtread_mutex_lock(&mutex);
     pthread_cond_wait(&cond,&mutex);
     printf("%#ld:我消费一辆跑车\n",pthread_self());
     phtread_mutex_unlock(&mutex);
    }
}
void *task4(void *arg)//创建消费者线程
{
    while(1)
    {
     sleep(1);
     phtread_mutex_lock(&mutex);
     phtread_cond_wait(&cond,&mutex);
     printf("%#ld:我消费一辆跑车\n",pthread_self());
     phtread_mutex_unlock(&mutex);
    }
}


int main(int argc, const char *argv[])
{
    pthread_t tid1,tid2,tid3,tid4;//定义四个线程
    if(pthread_create(&tid1,NULL,task1,NULL))
      {
         perror("create tid1 error");
         return -1;
      }
    if(pthread_create(&tid2,NULL,task2,NULL))
    {
        perror("creaate tid2 error");
        return -1;
    }
    if(pthread_create(&tid3,NULL,task3,NULL))
      {
         perror("create tid3 error");
         return -1;
      }

     if(pthread_create(&tid4,NULL,task4,NULL))
      {
         perror("create tid4 error");
         return -1;
      }
     pthread_cond_init(&cond,NULL);//初始化条件变量
     pthread_mutex_init(&mutex,NULL);//初始化锁
    printf("tid1=%#lx,tid2=%#lx,tid3=%#lx,tid4=%#lx",\
            tid1,tid2,tid3,tid4);//输出四个线程
    //回收四个线程的资源
     pthread_join(tid1,NULL);
     pthread_join(tid2,NULL);
     pthread_join(tid3,NULL);
     pthread_join(tid4,NULL);
     pthread_cond_destory(&cond);  //释放条件变量
     pthread_mutex_destory(&mutex);//释放锁
    return 0;
}
 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值