利用线程的同步和互斥解决两个消费者两个生产者一个临界区问题

本文通过一个家庭成员间的水果传递场景,演示了使用POSIX线程(PTHREADS)和信号量(SEM)进行进程间通信和同步的方法。在示例中,父线程购买苹果并放置在盘子中,随后被女线程取走食用;同时,母线程购买橘子并放入盘子,然后由男线程取走食用。整个过程展示了如何利用锁和信号量确保资源访问的互斥性和同步。

//没长期测试 ,发出来让大家看看

#include<stdio.h>

#include<semaphore.h>
#include<pthread.h>
#include<stdlib.h>


pthread_t fa,ma,boy,gr;
sem_t sem_fa,sem_ma,sem_boy,sem_gr;
pthread_mutex_t mutex;


void *father(void *arg)
{
while(1)
{
        pthread_mutex_lock(&mutex);
    printf("父亲买一个苹果\n");
     sem_wait(&sem_fa);
    sleep(2);
     printf("父亲把苹果放在盘子里\n");
     sem_post(&sem_gr);
}
pthread_exit(NULL);
}




void *girl(void *arg)
{
while(1)

{
      pthread_mutex_unlock(&mutex);
sem_wait(&sem_gr);
printf("女儿从盘子里拿走苹果\n");
sleep(1);
sem_post(&sem_fa);
printf("女儿吃苹果\n");
sleep(5);
}
pthread_exit(NULL);
}


void  *mather(void *arg)
{
while(1)
{
     pthread_mutex_lock(&mutex);
    printf("母亲买一个橘子\n");
     sem_wait(&sem_ma);
    sleep(2);
     printf("母亲把橘子放在盘子里\n");
     sem_post(&sem_boy);
}
pthread_exit(NULL);
}
void *boy1(void *arg)
{
while(1)

{
     pthread_mutex_unlock(&mutex);
sem_wait(&sem_boy);
printf("儿子从盘子里拿走橘子\n");
sleep(1);
sem_post(&sem_ma);
printf("儿子吃掉橘子\n");

        sleep(5);
}
pthread_exit(NULL);
}


int main()
{
sem_init(&sem_fa,0,1);
sem_init(&sem_gr,0,0);
sem_init(&sem_ma,0,1);
sem_init(&sem_boy,0,0);
pthread_mutex_init(&mutex,NULL);
    pthread_mutex_lock(&mutex);
if(pthread_create(&fa,NULL,father,NULL)!=0)
{
perror("thread fa create fail\n");
exit(0);


}

if(pthread_create(&gr,NULL,girl,NULL)!=0)
{
perror("thread girl create fail\n");
exit(0);


}
pthread_mutex_unlock;
    pthread_mutex_lock(&mutex);
if(pthread_create(&ma,NULL,mather,NULL)!=0)
{
perror("thread mather create fail\n");
exit(0);


}
if(pthread_create(&boy,NULL,boy1,NULL)!=0)
{
perror("thread boy1 create fail\n");
exit(0); 


}
pthread_mutex_unlock;
pthread_join(fa,NULL);
pthread_join(gr,NULL);
pthread_join(ma,NULL);
pthread_join(boy,NULL);


sem_destroy(&sem_fa);
sem_destroy(&sem_gr);
sem_destroy(&sem_ma);
sem_destroy(&sem_boy);


pthread_mutex_destroy(&mutex);


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值