第一关
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#define SIZE 10
int in = 0;
int out = 0;
int buffer[SIZE];
sem_t empty;
sem_t full;
pthread_mutex_t mutex;
void *Producer()
{
int nextp = 0;
int i = 0;
for(; i < 10; ++i)
{
int time = rand() % 10 + 1;
usleep(time*100000);
sem_wait(&empty);
pthread_mutex_lock(&mutex);
nextp = nextp + 1;
buffer[in] = nextp;
printf("Produce one message:%d\n", nextp);
fflush(stdout);//printf后请一定调用这句刷新输出缓存
in = (in + 1) % SIZE;
pthread_mutex_unlock(&mutex); //互斥锁解锁
sem_post(&full);
}
}
void *Consumer()
{
int nex=0;
for(int i=0;i<10;i++)
{
int time = rand()%10+1;
pthread_mutex_lock(&mutex);
nex = nex + 1;
buffer[in] = nex;
printf("Consume one message:%d\n", nex);
fflush(stdout);//printf后请一定调用这句刷新输出缓存
in = (in + 1) % SIZE;
pthread_mutex_unlock(&mutex); //互斥锁解锁
sem_post(&full);
}
}
int main()
{
sem_init(&empty, 0, 10); //信号量初始化(最多容纳10条消息,容纳了10条生产者将不会生产消息)
sem_init(&full, 0, 0);
pthread_mutex_init(&mutex, NULL); //互斥锁初始化
pthread_t producid;
pthread_t consumid;
pthread_create(&producid, NULL, Producer, NULL); //创建生产者线程
pthread_create(&consumid, NULL, Consumer, NULL); //创建消费者线程
pthread_join(producid, NULL);
pthread_join(consumid, NULL);
sem_destroy(&empty); //信号量的销毁
sem_destroy(&full);
pthread_mutex_destroy(&mutex); //互斥锁的销毁
return 0;
}
第二关
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
#include <pthread.h>
sem_t apple;
sem_t orange;
sem_t empty;
pthread_mutex_t mutex;
void *Dad()
{
int nextp = 0;
int i = 0;
for(i = 0; i < 10; ++i)
{
int time = rand() % 10 + 1; //随机使程序睡眠0点几秒
usleep(time*100000);
sem_wait(&empty);
pthread_mutex_lock(&mutex);
if(nextp == 0)
{
printf("爸爸放入了一个苹果\n");
}
else
{
printf("爸爸放入了一个桔子\n");
}
fflush(stdout);
pthread_mutex_unlock(&mutex); //互斥锁解锁
if(nextp == 0)
{
sem_post(&apple);
}
else
{
sem_post(&orange);
}
nextp = 1 - nextp;
}
}
void *Daughter()
{
while(1)
{
int time = rand() % 10 + 1; //随机使程序睡眠0点几秒
usleep(time * 100000);
sem_wait(&apple);
pthread_mutex_lock(&mutex);
printf("女儿取了一个苹果\n") ;
fflush(stdout);
pthread_mutex_unlock(&mutex); //互斥锁解锁
sem_post(&empty);
}
}
void *Son()
{
while(1)
{
int time = rand() % 10 + 1;
sem_wait(&orange);
pthread_mutex_lock(&mutex);
printf("儿子取了一个桔子\n") ;
fflush(stdout);
pthread_mutex_unlock(&mutex); //互斥锁解锁
sem_post(&empty);
}
}
int main()
{
sem_init(&empty, 0, 5); //信号量初始化
sem_init(&orange, 0, 0);
sem_init(&apple, 0, 0);
pthread_mutex_init(&mutex, NULL); //互斥锁初始化
pthread_t dadid;
pthread_t daughterid;
pthread_t sonid;
pthread_create(&dadid, NULL, Dad, NULL); //创建爸爸线程
pthread_create(&daughterid, NULL, Daughter, NULL); //创建女儿线程
pthread_create(&sonid, NULL, Son, NULL); //创建儿子线程
pthread_join(daughterid, NULL);
pthread_join(sonid, NULL);
sem_destroy(&empty); //信号量的销毁
sem_destroy(&apple);
sem_destroy(&orange);
pthread_mutex_destroy(&mutex); //互斥锁的销毁
return 0;
}