您的位置:首页 > 其它

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

2017-10-26 22:44 405 查看
//没长期测试 ,发出来让大家看看

#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);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  线程
相关文章推荐