这里的多是指多种类型
原理
同步关系:父亲和女儿 母亲和儿子
互斥关系:父亲和母亲
儿子和女儿间没有同步互斥关系
代码实现
#include<pthread.h>
#include<semaphore.h>
#include<iostream>
#include<unistd.h>
#include<time.h>
sem_t plate, apple, orange;
void* father(void* no)
{
while (true)
{
sem_wait(&plate);
//不要使用using namespace std
std::cout << "father input a apple" << std::endl;
sem_post(&apple);
sleep(1);
}
}
void* mother(void* no)
{
while (true)
{
sem_wait(&plate);
std::cout << "mother input a orange" << std::endl;
sem_post(&orange);
sleep(2);
}
}
void* son(void* no)
{
while (true)
{
sem_wait(&orange);
std::cout << "son eat a orange" << std::endl;
sem_post(&plate);
sleep(3);
}
}
void* daughter(void* no)
{
while (true)
{
sem_wait(&apple);
std::cout << "daughter eat a apple" << std::endl;
sem_post(&plate);
sleep(3);
}
}
int main()
{
//palte为互斥量,初始值设为1
sem_init(&plate, 0, 1);
sem_init(&apple, 0, 0);
sem_init(&orange, 0, 0);
pthread_t pfather,pmother, pson, pdaughter;
pthread_create(&pfather, NULL, &father, NULL);
//pthread_join(pfather, NULL); 错误示例,会阻塞在这里
pthread_create(&pmother, NULL, &mother, NULL);
pthread_create(&pson, NULL, &son, NULL);
pthread_create(&pdaughter, NULL, &daughter, NULL);
//阻塞等待线程结束
pthread_join(pmother, NULL); //pthread_join会阻塞等待线程结束。如果创建线程立即join会一直阻塞在那里
pthread_join(pfather, NULL);
pthread_join(pfather, NULL);
pthread_join(pson, NULL);
//销毁信号量
sem_destroy(&plate);
sem_destroy(&apple);
sem_destroy(&orange);
pthread_exit(NULL);
}