#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/stat.h>
#include <fcntl.h>
sem_t sem1,sem2,sem3,sem4;
void *fun1(void *a)
{
while(1)
{
sleep(1);
sem_wait(&sem1);
printf("春\t");
sem_post(&sem2);
}
pthread_exit(NULL);
}
void *fun2(void *a)
{
while(1)
{
// sleep(1);
sem_wait(&sem2);
printf("夏\t");
sem_post(&sem3);
}
pthread_exit(NULL);
}
void *fun3(void *a)
{
while(1)
{
// sleep(1);
sem_wait(&sem3);
printf("秋\t");
sem_post(&sem4);
}
pthread_exit(NULL);
}
void *fun4(void *a)
{
while(1)
{
// sleep(1);
sem_wait(&sem4);
printf("冬\n");
sem_post(&sem1);
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
pthread_t tid1,tid2,tid3,tid4;
sem_init(&sem1,0,1);
sem_init(&sem2,0,0);
sem_init(&sem3,0,0);
sem_init(&sem4,0,0);
if(pthread_create(&tid1,NULL,fun1,NULL)!=0)
{
perror("ptcreat2");
return -1;
}
if(pthread_create(&tid2,NULL,fun2,NULL)!=0)
{
perror("ptcreat2");
return -1;
}
if(pthread_create(&tid3,NULL,fun3,NULL)!=0)
{
perror("ptcreat2");
return -1;
}
if(pthread_create(&tid4,NULL,fun4,NULL)!=0)
{
perror("ptcreat2");
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;
}
使用无名信号量实现循环输出春,夏,秋,冬
最新推荐文章于 2024-09-01 10:20:57 发布