作业:
使用无名信号量实现循环输出 春、夏、秋、冬
程序代码:
#include <myhead.h>
sem_t sem1,sem2,sem3,sem4;
void *fun1(void *ggg)
{
while(1)
{
sem_wait(&sem4);
printf("春");
fflush(stdout);
sem_post(&sem3);
}
pthread_exit(NULL);
}
void *fun2(void *ggg)
{
while(1)
{
sem_wait(&sem3);
printf("夏");
fflush(stdout);
sem_post(&sem2);
}
pthread_exit(NULL);
}
void *fun3(void *ggg)
{
while(1)
{
sem_wait(&sem2);
printf("秋");
fflush(stdout);
sem_post(&sem1);
}
pthread_exit(NULL);
}
void *fun4(void *ggg)
{
while(1)
{
sem_wait(&sem1);
printf("冬\t");
fflush(stdout);
sem_post(&sem4);
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
pthread_t tid1,tid2,tid3,tid4;
sem_init(&sem1,0,0);
sem_init(&sem2,0,0);
sem_init(&sem3,0,0);
sem_init(&sem4,0,1);//信号量sem4先给进程1资源
if(pthread_create(&tid1,NULL,fun1,NULL)!=0)
{
perror("ptcreat1");
return -1;
}
if(pthread_create(&tid2,NULL,fun2,NULL)!=0)
{
perror("ptcreat2");
return -1;
}
if(pthread_create(&tid3,NULL,fun3,NULL)!=0)
{
perror("ptcreat3");
return -1;
}
if(pthread_create(&tid4,NULL,fun4,NULL)!=0)
{
perror("ptcreat4");
return -1;
}
sem_destroy(&sem1);
sem_destroy(&sem2);
sem_destroy(&sem3);
sem_destroy(&sem4);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_join(tid3,NULL);
pthread_join(tid4,NULL);
return 0;
}